1. 최대 장점
- Mybatis의 최대 장점은 편리한 동적쿼리이기에 가장 중요하다. 회사에서도 가장 중요한 것 같다. if, choose(when, otherwise), where, foreach 로 나누어 공부해보자
2. if문
<select id="findActiveBlogWithTitleLike" resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
3. choose - when - otherwise
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
- 다중 조건이다 if-else와 같다고 생각하면됨
- choose - when 조건 1 (if) - when 조건 2 (else if).. - otherwise (else)
4. foreach
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT * FROM POST P
<where>
<foreach item="item" index="index" collection="list" open="ID in ("
separator="," close=")" nullable="true">
#{item}
</foreach>
</where>
</select>
- 컬렉션을 반복 처리할 때 사용하며 파라미터로 List를 전달하면 된다.
- item : 넘어온 List 파라미터를 담아 반복문을 돌리기 위한 item 이라고 생각하면 됨
- index : 생략 가능하며 그냥 넘어온 요소의 인덱스라고 생각하면 편할듯
- collection : 실제로 반복할 넘어온 파라미터 자체라고 생각하자
- open : 반복할 시작 문구를 지정한다. "ID in (" 이거로 시작해서 안에 반복문을 돌린다.
- close : 반복하고 난 뒤 뒤에 붙힐 close 문구를 지정한다.
- separator : 각 요소를 연결할 때 사용할 구분자이다. 여기서는 IN이니까 "," 콤마로 구분해서 해야하기에 콤마가 들어갔다.
5. XML CDATA
<if test="itemName != null and itemName != ''">
and item_name like concat('%',#{itemName},'%')
</if>
<if test="maxPrice != null">
<![CDATA[
and price <= #{maxPrice}
]]>
</if>
- XML에서는 부등호, & 기호를 그대로 사용하기 위해 CDATA 문법을 사용한다. 이 구문 안에서는 부등호 등이 단순 문자로 인식된다.