
동적 쿼리
<select id="findActiveBlogWithTitleLike" resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
<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>
trim (where, set)
- 동적 쿼리 작성 시 where 문을 어떻게 해야 할지 애매할 때 사용
- where 절 안에 넣어 두면 시작이 AND로 와도 AND를 where 문으로 치환해줌
- 예) SELECT * FROM BLOG WHERE title like #{title}
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
foreach
- 컬렉션을 반복 처리할 때 사용한다.
where in (1,2,3,4,5,6) 와 같은 문장을 쉽게 완성할 수 있다.
<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>