Spring - MyBatis 연동
Spring - MyBatis 연동
1. spring-jdbc / spring-tx / mybatis / mybatis-spring
위 4가지 pom.xml에 추가
org.mybatis mybatis 3.4.6 org.mybatis mybatis-spring 1.3.2 org.springframework spring-jdbc ${org.springframework-version} org.springframework spring-tx ${org.springframework-version}
2. root-context.xml에 SqlSessionFactoryBean 등록
3. Mapper 인터페이스 작성 ( SampleMapper.java )
package org.skwzz.mapper; import org.apache.ibatis.annotations.Select; public interface SampleMapper { @Select("SELECT sysdate FROM dual") public String getTime(); }
일반적으로 쿼리는 xml 에 작성하지만 테스트 용으로 MyBatis의 어노테이션을 사용해 작성
테스트 후 변경할 예정
4. root-context.xml에 해당 mapper를 스캔 가능하게 설정
체크 후 밑의 코드 추가
5. Mapper 테스트 클래스 작성 후 테스트 ( SampleMapperTests.java )
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml") @Log4j public class SampleMapperTests { @Setter(onMethod_ = {@Autowired}) private SampleMapper sampleMapper; @Test public void testGetTime() { log.info(sampleMapper.getClass().getName()); log.info(sampleMapper.getTime()); } }
테스트 결과
6. 연결 확인 됬으므로 XML Mapper 사용해보기
SampleMapper.java 인터페이스에 XML로 실행할 코드 작성
public interface SampleMapper { @Select("SELECT sysdate FROM dual") public String getTime(); public String getTimeUseMapperXML(); }
SampleMapper.xml 파일을 생성할건데
1. Mapper Interface와 같은 위치에 생성
2. src/main/resources 에 폴더 생성 후 저장 ( 이걸로 진행함 )
- 2로 진행할 시 폴더를 한 번에 하나씩 저장. 한꺼번에 할 경우 제대로 인식이 되지 않는 문제가 있음
파일 생성 후
- mapper dtd 작성 ( LINK ) 들어가서 mapper.dtd로 검색하면 나오는 예제가 있음 복붙하면됨
- mapper namespace 설정
- 쿼리 작성 (쿼리 작성시 세미콜론 붙이면 에러남)
SELECT sysdate FROM dual
신경써야 할 점
태그의 namespace 속성을 사용 할 Mapper 인터페이스와 동일하게 맞춰야함.
쿼리의 id값은 메소드의 이름과 동일해야함
7. 테스트
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml") @Log4j public class SampleMapperTests { @Setter(onMethod_ = {@Autowired}) private SampleMapper sampleMapper; @Ignore @Test public void testGetTime() { log.info(sampleMapper.getClass().getName()); log.info(sampleMapper.getTime()); } @Test public void testGetTimeUseMapperXMl() { log.info(sampleMapper.getTimeUseMapperXML()); } }
테스트 결과
from http://skwzz.tistory.com/87 by ccl(A) rewrite - 2020-03-06 23:21:26
댓글
댓글 쓰기