Spring

[spring] (1) springboot, mysql, mybatis 연결, DB에서 데이터가져오기

우주유령 2022. 10. 20. 18:21
728x90
반응형

SpringBoot에서 DB를 연결하고 데이터를 가져오는 방법을 알아보자.

 

SpringBoot에서 DB에 연결하려면 아래가 필요하다.

  • JDBC driver
  • DB connector
  • MyBatis

spring boot의 dependency를 찾는 일은 어렵다.

워낙 방대해서 그냥 블로그나, 강의에서 하라는 대로 따라하되, dependency를 추가할때는 maven repository에서 직접 가져다 추가하는게 가장 좋은 방법인 것 같다.

SpringBoot에 MySql연결하기

SpringBoot MySql로 검색하거나, SpringBoot에서 직접 돌아다니며 DB연결 예제를 찾을 수 있다.

https://spring.io/guides/gs/accessing-data-mysql/

 

Accessing data with MySQL

this guide is designed to get you productive as quickly as possible and using the latest Spring project releases and techniques as recommended by the Spring team

spring.io

이 페이지에 보면 간단한 예제가 나와있다. 예제와 달리 우리는 jpa를 사용하지 않고 jdbc와 mybatis를 추가해 줄 것이다.

mysql에서도 spring과의 연결 방법이 나와있긴 하지만, spring-boot는 없다. 찾아보기 힘드니 그냥 springboot 페이지에서 제공해주는 예제를 따라하도록 하자.

 

gradle dependency추가

  • mysql-connector-j
  • spring-boot-starter-jdbc

또는 spring initilzr에서 dependency로 아래를 추가한다.

  • mysql driver
  • spring data jdbc

application.properties에 추가

#mybatis config
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

starter

starter가 붙은 애들은 spring → springboot로 넘어오면서 application.properties에서 설정 가능하도록 만들어진 애들이다. 그렇지 않은 것들은 springConfig를 만들어서 설정해줘야 하는 번거로움이있다. jdbc도 starter패키지이므로 application.properties에서 설정 가능하다.

SpringBoot에서 MyBatis 연결하기

Mybatis와 SpringBoot를 어떻게 연결하는지 알아보기 위해 MyBatis 공식 홈페이지로 들어가보자

http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

 

mybatis-spring-boot-autoconfigure – Introduction

Introduction What is MyBatis-Spring-Boot-Starter? The MyBatis-Spring-Boot-Starter help you build quickly MyBatis applications on top of the Spring Boot. By using this module you will achieve: Build standalone applications Reduce the boilerplate to almost z

mybatis.org

  • mybatis > products > integration > spring boot starter

여기에서 관련 설명, config doc을 읽을 수 있다.

 

dependency추가

  • mybatis-spring-boot-starter

또는 spring initilzr에서 dependency로 아래를 추가한다.

  • mybatis framework

application.properties 추가

# mybatis config
mybatis.mapper-locations=/mapper/**/*.xml

 

다음 포스팅에서는 데이터를 가져오는 비즈니스 로직을 연결해 보겠다.

728x90
반응형