SPRING

[Mybatis] DAO 구현 방법 2 (mapper interface / annotation)

nang. 2019. 6. 3. 20:14
반응형
SMALL

< mapper interface 사용 방법>

* interface를 정의하고 어노테이션을 사용하여 쿼리 작성

public interface CommentMapper {

    @Select({"select comment_no, user_id, comment_content, reg_date 

                 from Comments where comment_no = #{commentNo)"})

    Comment selectById(Long commentNo);

}

 

 

< DAO class >

 

public class CommentSessionRepository {

    public Comment selectById(Long commentNo) {

        ...

        return sqlSession.getMapper(CommentMapper.class).selectById(commentNo);

        // interface에 정의해 놓은 메소드를 직접 호출

        // 매퍼의 메소드 호출 --> 쿼리를 실행해라~

}

* getMapper

: interface mapper를 구해옴

 

* 그 매퍼의 메소드 호출

: 해당 쿼리 실행

 

* interface에 메소드로 정의해놓은 이유

: 만약 메소드명이 긴데 오타가 나면 메소드기때문에 컴파일 에러가 남

--> XML 방식에서는 "~~" 문자로 들어가기때문에 오타나도 몰라

 

* Spring을 사용하면 return 부분 없어도 돼

: 알아서 해주기 때문

: @Autowired 해서 Mapper 클래스를 주입시킴

반응형
LIST

'SPRING' 카테고리의 다른 글

[Mybatis] Dao 구현 방법 1 (mapper.xml / DAO class)  (0) 2019.06.03
DAO Support Class  (0) 2019.05.13
[SimpleJdbcInsert]  (0) 2019.05.13
[NamedParameterJdbcTemplate]  (0) 2019.05.13
[JdbcTemplate] 그 외 메소드 / 가변 길이 인자 지원  (0) 2019.05.13