티스토리 뷰

Study/Spring

[Spring] Mybatis 연동 (2)

그징그징 2018. 12. 26. 10:46

[Spring] Mybatis 연동 (2)


interface 생성 후 JUnit으로 테스트




1. 패키지 생성 후 interface Mapper 생성




2. TestMapper.java 에 코드 작성




3. JUnit 으로 테스트(src/test/java 밑에)





ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@42dafa95] to prepare test instance [com.sora.shop.db.InterfaceMapperTest@140c9f39]

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.sora.shop.db.InterfaceMapperTest': Unsatisfied dependency expressed through field 'mapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.sora.shop.mapper.TestMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)

at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)

...

..



Exception 이 발생합니다.


Autowired 자동 주입이 안되는 상황으로 root-context.xml에 mapper interface를 스캔하게 해줘야합니다.



root-context.xml 의 namespace 탭에서 mybatis-spring을 체크해줍니다.(저장)


그 후 Source 탭으로 이동하여 코드를 작성합니다.


<mybatis-spring:scan base-package="com.sora.shop.mapper"/> 


해당 패키지안의 것을 스캔해서 Autowired 어노테이션을 이용하여 주입해줍니다.




4. JUnit 테스트 재 시도





5. Xml을 이용하기 위한 기본 셋팅


src/main/resources 밑에 인터페이스 맵퍼를 만든 패키지와 동일한 '폴더들'을 생성합니다.

저 같은 경우

/src/main/resources/com/sora/shop/mapper/TestMapper.xml

을 생성합니다.



xml 파일 이름과 interface 이름은 같아야하고 패키지도 같아야합니다.

(다르게 하고 테스트시에 에러 납니다.)




6. interface mapper 수정





7. 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.sora.shop.mapper.TestMapper">

  <select id="sysdate2" resultType="String">

    select sysdate() from dual

  </select>

</mapper> 


xml을 작성합니다.


namespace는 interface의 경로를 지정해줍니다.

select 태그 안에 id는 6번에서 만들어준 함수명을 입력해줍니다.

그리고 select 문을 태그안에 작성합니다.




8. JUnit 으로 테스트







'Study > Spring' 카테고리의 다른 글

[Spring] BootStrap 사용하기  (1) 2018.12.26
[Spring] web.xml (한글 설정)  (0) 2018.12.26
[Spring] Mybatis 연동 (1)  (0) 2018.12.24
[Spring] Mysql과 JUnit (2)  (0) 2018.12.24
[Spring] root-context.xml와 servlet-context.xml  (0) 2018.12.24
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   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
글 보관함