Mybatis는 SQL Mapper파일에 SQL을 작성하며 DAO에서 SqlSession 객체가 SQL mapper 파일을 참조하게 된다.
[1] Mapper 만들기
첫 번째. SQL Mapper파일에서 가장 먼저 XML과 DTD선언을 해준다.
(설정파일(config)에서도 선언해준다. 단, mapper를 config로 바꿔주면 된다.)
<?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를 작성한다.
(네임스페이스란? https://ko.wikipedia.org/wiki/%EC%9D%B4%EB%A6%84%EA%B3%B5%EA%B0%84D)
<mapper namespace="ExampleMapper">
세 번째. SQL문에 따라서 작성한다.
-
SELECT - <select>SQL문</select>
--> resultType : id와 함께 필수속성으로 select의 결과로 반환된 resultSet이 매핑된 객체의 타입이다.
--> resultMap : resultType 대신 사용 가능하다. (단순 테이블 조회가 아닌 join을 포함할 때
하나의 객체로 매핑할 수 없기 때문에 사용함) -
INSERT - <insert>SQL문</insert>
-
UPDATE - <update>SQL문</update>
-
DELETE - <delete>SQL문</delete>
네 번째. 설정파일 등록 및 DAO
<mappers>
<mapper resource="mybatis/CommentMapper.xml"/>
<mapper resource="mybatis/CommentResultMapMapper.xml"/>
</mappers>
config.xml파일의 <mappers>태그 안에 작성한 Mapper파일을 등록한다.
이후 DAO에서 SqlSession객체가 등록된 Mapper파일을 참조하여 SQL문을 실행할 수 있다.
[2] Annotation을 이용한 Mapper
위에서의 예 처럼 xml파일로 Mapper를 만드는 방법도 있지만, 어노테이션(annotation)을 이용할 수도 있다.
public Integer insertComment(Comment comment) {
SqlSession sqlSession = getSqlSessionFactory().openSession();
try {
return sqlSession.getMapper(CommentMapper.class).insertComment(comment);
} finally {
sqlSession.commit();
sqlSession.close();
}
}
org.apache.ibatis.annotations.~ 을 import하여 @Select(), @Insert(), @Update(), @Delete()안에
sql문을 작성하고 @Result로 컬럼명과 프로퍼티를 매핑하고 @Results로 묶어 사용할 수 있다.
<mappers>
<mapper class="mybatis.CommentMapper"/>
</mappers>
마찬가지로 config.xml파일의 <mappers>태그 안에 작성한 클래스를 등록한다.
public Integer insertComment(Comment comment) {
SqlSession sqlSession = getSqlSessionFactory().openSession();
try {
return sqlSession.getMapper(CommentMapper.class).insertComment(comment);
} finally {
sqlSession.commit();
sqlSession.close();
}
}
이때 DAO에서는 위와 같이 sqlSession.getMapper.~를 사용할 수 있다.