티스토리 뷰

Spring-Boot

spring boot mybatis 연동

SonSeungWoo 2019. 2. 6. 15:09

spring boot mybatis 연동

오늘은 spring boot와 mybatis를 간단하게 연동 테스트를 해보겠다. 일단 spring boot 프로젝트를 생성하고 아래와 같이 디펜던시를 받자.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

City라는 class를 만들자.

@Data
@Alias("city")
public class City {
private Long id;
private String name;
private String country;
private Long population;

public City() {
}

public City(String name, String country, Long population) {
this.name = name;
this.country = country;
this.population = population;
}
}

@Alias 어노테이션은 xml에서 아래와 같이 resultType 별칭으로 사용할 수 있다. 사용하지 않아도 무방하다.

대신 resultType에 classpath 경로를 적어줘야한다. 예) com.ssw.City

<select id="selectCityById" resultType="city">

그다음 mapper 인터페이스를 작성하자

@Mapper
public interface CityMapper {
City selectCityById(Long id);
List<City> selectAllCity();
void insertCity(City city);

@Select("select * from city where name = #{name}")
City findByName(@Param("name") String name);
}

@select 어노테이션은 일반 쿼리를 작성해서 사용할 수 있다. 하지만 mybatis를 사용하는 큰이유는 쿼리를 xml로 따로 관리하는것인데 흠...사용을 하는건 머 본인에게 맡기겠다. 그리고 위 메소드 명은 mybatis select, insert등 id명과 일치해야한다. 그리고 이제 서비스를 작성하자.

@Service
@Transactional
@RequiredArgsConstructor
public class CityService {

private final CityMapper cityMapper;

public City getCityById(Long id) {
return cityMapper.selectCityById(id);
}

public List<City> getAllCity() {
return cityMapper.selectAllCity();
}

public City findByName(String name) {
return cityMapper.findByName(name);
}

public void addCity(City city) {
cityMapper.insertCity(city);
}
}

이제 mapper xml 작성을 하자. 여기서 mapper.xml은 resource 폴더밑 mapper 인터페이스와 같은 패키지로 만들어야한다,

예)com.ssw.CityMapper 이렇게 있다면 resource 폴더 하위에 com.ssw.CityMapper.xml 이렇게 해줘야한다.

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.github.ssw.springbootmybatis.CityMapper">

<resultMap id="cityResult" type="CityDto">
<result column="id" property="id" />
<result column="name" property="name" />
<result column="country" property="country" />
<result column="population" property="population" />
</resultMap>

<select id="selectCityById" resultType="city">
SELECT ID
,NAME
,COUNTRY
,POPULATION
FROM CITY
WHERE ID = #{id}
</select>

<select id="selectAllCity" resultMap="cityResult">
SELECT ID
,NAME
,COUNTRY
,POPULATION
FROM CITY
</select>

<insert id="insertCity">
INSERT INTO CITY (NAME, COUNTRY, POPULATION)
VALUES (#{name}, #{country}, #{population})
</insert>

</mapper>

그리고 properties 파일에 다음과 설정을 해주자 h2 데이테베이스를 사용하기 때문 설정을 해줘야한다.

spring.datasource.url=jdbc:h2:mem:test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

mybatis.type-aliases-package=com.github.ssw.springbootmybatis
spring.datasource.schema=classpath:scheme.sql

그리고 spring.datasource,schema는 스프링부트 실행시 테이블 생성및 데이터 생성하기 위해 설정을 해주고 아래와 같이 resource하위에 scheme.sql파일을 추가해주자.

DROP TABLE IF EXISTS CITY;

CREATE TABLE CITY (ID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR, COUNTRY VARCHAR, POPULATION INT);

INSERT INTO CITY (NAME, COUNTRY, POPULATION) VALUES ('San Francisco', 'US', 10000);
INSERT INTO CITY (NAME, COUNTRY, POPULATION) VALUES ('서울', 'KR', 20000);
INSERT INTO CITY (NAME, COUNTRY, POPULATION) VALUES ('東京', 'JP', 30000);
INSERT INTO CITY (NAME, COUNTRY, POPULATION) VALUES ('부산', 'KR', 40000);

이런식으로 작성을 하고 테스트를 하면 잘 될것이다. 간단한 예제소스는 여기에 있다.

'Spring-Boot' 카테고리의 다른 글

Spring boot for Apache Kafka  (2) 2019.06.28
spring boot MessageSource 다국어처리  (0) 2019.02.08
spring boot Transaction(@Transactional)  (0) 2018.01.15
spring xml을 java config로 설정하기  (0) 2017.08.16
공지사항
최근에 올라온 글
최근에 달린 댓글
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함