본문으로 바로가기

Mapper테스트

 MyBatis-Spring은 Mapper 인터페이스를 이용해서 실제 SQL 처리가 되는 클래스를 자동으로 생성함. 따라서 개발자들은 인터페이스와 SQL만을 작성하는 방식으로도 모든 JDBC처리를 끝낼 수 있음.


TimeMapper 테스트코드 생성


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
package org.zeorck.persistence;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.zeorck.mapper.TimeMapper;
 
import lombok.Setter;
import lombok.extern.log4j.Log4j;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
//JAVA설정을 사용하는 경우
//@ContextConfiguration(classes= {RootConfig.class})
@Log4j
public class TimeMapperTests {
 
    @Setter(onMethod_=@Autowired)
    private TimeMapper timeMapper;
    
    @Test
    public void testGetTime() {
        log.info(timeMapper.getClass().getName());
        log.info(timeMapper.getTime());
    
    }
}
 
cs


TimeMapperTests클래스는 TimeMapper의 테스트 코드 . 만약 정상적으로 동작한다 스프링 내부에는 TimeMapper타입으로

 만들어진 스프링 객체(빈)가 존재한다는 뜻.


timeMapper.getClass().getNAme()은 실제 동작하는 클래스의 이름을 확인해 주는데 실행 결과를 보면 개발 시 인터페이스만 만들어 주었는데 

내부적으로 적당한 클래스가 만들어 진 것을 확인 할 수 있습니다 .(AOP때 자세히나옴 아직 몰라도됨.)

 여기서는 스프릥이 인터페이스를 이용해서 객체를 생성한다는 사실에 주목해야함.


테스트결과 (자바도 똑같이 )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@42e26948, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@57baeedf, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@343f4d3d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@53b32d7, org.springframework.test.context.transaction.TransactionalTestExecutionListener@5442a311, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@548e7350]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from URL [file:src/main/webapp/WEB-INF/spring/root-context.xml]
INFO : org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext@6536e911: startup date [Fri Dec 14 19:09:27 KST 2018]; root of context hierarchy
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
WARN : com.zaxxer.hikari.util.DriverDataSource - Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
INFO : org.zeorck.persistence.TimeMapperTests - com.sun.proxy.$Proxy22
INFO : org.zeorck.persistence.TimeMapperTests - 2018-12-14 19:09:29
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@6536e911: startup date [Fri Dec 14 19:09:27 KST 2018]; root of context hierarchy
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.
 
cs


▶XML  매퍼와 같이 쓰기 

MyBatis를 이용해서 SQL을 처리할 때 어노테이션을 이용하는 방식이 편리하기는 하지만,SQL이 복잡하거나 길어지는 경우에는 어노테이션 보다 XML을 이용하는 방식을 더 선호하게됨. 다행히도 MyBatis-Spring의 겨우 MApper 인터페이스와 XML을 동시에 이용할 수 있음.


XML을 작성해서 사용할 때에는 XML 파일의 위치와 XML파일에 지정하는 namespace속성이 중요한데 ,XML파일 위치의 경우 Mapper인터페이스가 있는 곳에 같이 작성해야하거나 밑에 사진처럼 src/main/resources 구조에 XML을 저장할 폴더를 생성할 수 있음.XML파일을 만들때 규칙은 따로 없지만 Mapper인터페이스와같은이름을 사용하는것이 가독성에 좋음.


src/main/resources  폴더에 org만들고 zeorck만들고 mapper만들어줌(한번에 만들지 말고 하나씩)

생성된 폴더에 TimeMapper.xml을 생성

XML파일에는 MyBatis의 XML매퍼에서 이용하는 태그에 대한 설정이 필요함.

http://www.mybatis.org/mybatis-3/ko/sqlmap-xml.html 여기서 확인.


Mapper인터페이스와 XML을 같이 이용해 보기 위해서 기존의 TimeMapper인터페이스에 추가적인 메서드를 선언함.



 TimeMapper인터페이스


1
2
3
4
5
6
7
8
9
10
11
12
package org.zeorck.mapper;
 
import org.apache.ibatis.annotations.Select;
 
public interface TimeMapper {
 
    @Select("SELECT sysdate FROM dual")
    public String getTime();
    
    public String getTime2();
}
 
cs


 TimeMapper인터페이스 추가 된 getTime2()를 보면 @Select와 같은 MyBatis의 어노테이션이 존재하지 않고 SQL 역시 존재하지 않는 것을 볼 수 있음.


실제 SQL은 XML을 이용해서 처리할 것이므로 , 셍성한  TimeMapper.xml을 이 같이 만들어줌


1
2
3
4
5
6
7
8
9
10
11
<?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="org.zeorck.mapper.TimeMapper">
 
<select id="getTime2" resultType="string">
SELECT sysdate FROM dual
</select>
</mapper>
 
cs

XML매핑 사용시 <mapper>태그의 namespace속성 값을 신경서야함.MyBatis는 Mapper인터페이스와 XML을 인터페이스의 이름과namespace속성 
값을 가지고 판단함.위같이 orgzeorck.mapper.TimeMapper 인터페이스가 존재하고,XML의<mapper namespace="orgzeorck.mapper.TimeMapper">와
동일한 이름이 존재하면 ,이를 병합해서 처리함. 따라서 위의 경우 메서드 선언은 인터페이스에 존재하고 SQL에 대한 처리는 XML을 이용하는 방식이라고 볼수있음.

<select> 태그의 id 속성의 값은 메서드의 이름과 동일하게 맞춰야함.<select>태그의 경우resultType속성을 가지는데 이 값은 인터페이스에 선언된 메서드의 리턴타입과 동일하게 작성

최종적인 확인을 위한 테스트  TimeMapperTests 클래스이용


1
2
3
4
5
6
7
@Test
    public void testGetTime2() {
        log.info("getTime2");
        log.info(timeMapper.getTime2());
    
    }
    
cs
추가하고 테스트 

테스트결과는  getTime()과 동일 하다   (자바 방식 도 동일 합니다 .)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
INFO : org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@42e26948, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@57baeedf, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@343f4d3d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@53b32d7, org.springframework.test.context.transaction.TransactionalTestExecutionListener@5442a311, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@548e7350]
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from URL [file:src/main/webapp/WEB-INF/spring/root-context.xml]
INFO : org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext@6536e911: startup date [Fri Dec 14 20:06:00 KST 2018]; root of context hierarchy
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
WARN : com.zaxxer.hikari.util.DriverDataSource - Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
INFO : org.zeorck.persistence.TimeMapperTests - getTime2
INFO : org.zeorck.persistence.TimeMapperTests - 2018-12-14 20:06:02
INFO : org.zeorck.persistence.TimeMapperTests - com.sun.proxy.$Proxy22
INFO : org.zeorck.persistence.TimeMapperTests - 2018-12-14 20:06:02
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@6536e911: startup date [Fri Dec 14 20:06:00 KST 2018]; root of context hierarchy
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
INFO : com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.
 
cs