❖ 해당 인터페이스 -> Mapper로 설정
: @Mapper 어노테이션을 사용하면 해당 인터페이스(Repository)를 Mapper로 등록할 수 있다.
❖ root-context.xml 설정
: component:-scan을 통해 조회를 할 수 있던 것 처럼 mapper도 스캔기능을 하는 태그가 있다.
Mapper로 등록할 인터페이스를 root-comtext.xml 파일에 mybatis:scan 태그를 사용해 등록하게 되면
해당 mapper의 proxy 를 스프링에 등록할 수 있다.
(기능별로 repository를 따로 관리할 것이기 때문에 base-package를 root package로 넣을 것)
1
|
<mybatis:scan base-package="com.spring.mybatis" annotation="org.apache.ibatis.annotations.Mapper"/>
|
cs |
+ NameSpace도 설정해주기 ! ( MyBatis-Spring 연동 모듈과 관련된 태그를 사용할 수 있다.)
1
2
3
4
5
|
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
|
cs |
* 기존 mapper.xml과 Dao를 사용해 mybatis를 사용하는게 아니기 때문에
sqlSessionTemplate는 필요하지 않다.(factoryBean은 필요 !)
❖ @Mapper - 인터페이스로 Mybatis 사용해보기
Repository 인터페이스에 쿼리문을 어노테이션을 사용해서 작성해준 뒤, 해당 메소드를 불러내는 형태로 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/*-context.xml"})
public class MybatisTest {
private String userId = "test";
@Autowired
private MybatisRepository repo;
@Test
void selectOneTest() {
repo.selectMemberById(userId);
}
@Test
void selectListTest() {
repo.selectListTest();
}
|
cs |
**** 만약 , mapper 인터페이스와 Mapper.xml 파일을 같이 사용하고 싶은 경우엔 ****
❖ Mapper.xml 의 namespace 설정
: mapper의 namespace에 사용하길 원하는 mapper 인터페이스의 경로를 넣어 맞춰주면 된다.
=> <mapper namespace="com.spring.mybatis.mybatis.MybatisRepository">
인터페이스와 Mapper.xml파일에 쿼리가 중복등록되면 안되기 때문에 짧은 쿼리는 인터페이스에,
동적쿼리를 사용하거나 복잡한 쿼리문은 mapper.xml 파일에 작성해서 쓰는 형태로 사용하면 된다 !
(but, 인터페이스 내에 xml 파일에 있는 메소드 선언까지도 다 있어야 함 !!)
'BackEnd > Spring' 카테고리의 다른 글
[Jwt] Jason Web Token :: JWT 로 로그인 처리하기 (0) | 2021.12.08 |
---|
댓글