mybatis는 크게 2가지로 자바파일을 이용하는 방법과 xml을 이용하는 방법 두가지가 존재한다
기본세팅
application.properties
#db연결
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/bootex?serverTimezone=Asia/Seoul
spring.datasource.username=root
spring.datasource.password=12345
pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
자바 어노테이션을 이용하는 방법
1. mapper 패키지를 만들고 mapperinterface를 만든다
BootMapper
package com.example.demo.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.example.demo.dto.User;
public interface BootMapper {
@Select("select * from user where age = #{age}")
public User getUserAge(@Param("age") int age ) throws Exception;
}
2. DTO 클래스인 User class를 생성한다
User
package com.example.demo.dto;
import lombok.Data;
import lombok.ToString;
@Data
//uid를 제외하여 출력
@ToString(exclude = {"uid"})
public class User {
String name;
String uid;
int age;
}
3. Application.java 에 @MapperScan을 등록하여 mapper를 스캔할 수 있도록 한다
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(value= {"com.example.demo.mapper"})
public class BootexApplication {
public static void main(String[] args) {
SpringApplication.run(BootexApplication.class, args);
}
}
4. JUnitTest를 하기 위해 @Autowired 를통해 BootMapper를 의존주입하여 mapperTest()를 실행한다.
package com.example.demo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.DataSource;
import org.junit.Ignore;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.demo.dto.User;
import com.example.demo.mapper.BootMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
class BootexApplicationTests {
@Autowired
private DataSource ds;
@Autowired
BootMapper mapper;
@Test
public void mapperTest() throws Exception{
User user = mapper.getUserAge(1);
System.out.println("User : "+user);
assertEquals("장친수", user.getName());
}
@Ignore @Test
public void testDataSource() throws Exception {
System.out.println("DS=" + ds);
try (Connection conn = ds.getConnection()) {
System.out.println("Cooooooooonn=" + conn);
assertThat(conn).isInstanceOf(Connection.class);
assertEquals(100, getLong(conn, "select 100"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
5. 결과
정상적으로 exclude한 uid를 제외하고 값이 출력 되는 것을 확인할수있다.
XML을 이용하는 방법
1. mapper 패키지를 만들고 mapperinterface를 만든다
BootMapper
package com.example.demo.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.example.demo.dto.User;
public interface BootMapper {
public User getUserAge(@Param("age") int age ) throws Exception;
}
2. src/main/resources 밑에 mappers폴더를 만든다.
3. mapper 밑에 bootMapper.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와 중복되지 않도록 네임스페이스 기재 -->
<mapper namespace="com.example.demo.mapper.BootMapper">
<select id="getUserAge" resultType="com.example.demo.dto.User">
select * from user where age = #{age}
</select>
</mapper>
※ namespace 는 mapper클래스와 동인한 패키지명을 입력(bootMapper interface) , id 는 메소드명과 일치해야한다
4. application.properties에 mapper의 위치를 등록한다(안할 경우 Mapper.xml을 찾지 못해 에러발생)
#mybatis
mybatis.mapper-locations=classpath:/mappers/*Mapper.xml
5. Application.java 에 @MapperScan을 등록하여 mapper를 스캔할 수 있도록 한다
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(value= {"com.example.demo.mapper"})
public class BootexApplication {
public static void main(String[] args) {
SpringApplication.run(BootexApplication.class, args);
}
}
6. JUnitTest를 하기 위해 @Autowired 를통해 BootMapper를 의존주입하여 mapperTest()를 실행한다.
package com.example.demo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.DataSource;
import org.junit.Ignore;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.demo.dto.User;
import com.example.demo.mapper.BootMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
class BootexApplicationTests {
@Autowired
private DataSource ds;
@Autowired
BootMapper mapper;
@Test
public void mapperTest() throws Exception{
User user = mapper.getUserAge(2);
System.out.println("User : "+user);
assertEquals("pooney", user.getName());
}
@Ignore @Test
public void testDataSource() throws Exception {
System.out.println("DS=" + ds);
try (Connection conn = ds.getConnection()) {
System.out.println("Cooooooooonn=" + conn);
assertThat(conn).isInstanceOf(Connection.class);
assertEquals(100, getLong(conn, "select 100"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
7. 결과
User name pooney, age 2가 정상적으로 출력되는 것을 확인 할 수 있다.
'Spring boot' 카테고리의 다른 글
Spring boot @RequestBody 로 JSON 데이터 받을 시 JSON parse error (2) | 2020.05.19 |
---|---|
Spring boot jsp와 Thymeleaf 사용하기 (2) | 2020.05.16 |
Spring boot Controller test (0) | 2020.05.15 |
Spring boot Interceptor (0) | 2020.05.15 |
Spring boot 프로젝트 생성 (0) | 2020.05.14 |