Spring
Mybatis 동적 SQL( if, choose(when,oterwise), trim(where,set) )
MyDiaryYo
2023. 5. 3. 19:16
마이바티스의 가장 강력한 기능 중 하나인 동적SQL을 처리하는 방법이다
1.if
동적SQL에서 가장 공통적으로 사용되는것으로 where의 일부로 포함될 수 있습니다
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
2.choose, when, otherwise
java에서 switch구문과 유사하며 Mybatis에서는 choose엘리먼트를 제공한다
<choose>는 switch를 <when>은 case를 의미한다
<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>
3.trim, where, set
prefix:실행할 쿼리의 <trim>문 안에 쿼리 가장 앞에 붙여준다
suffix:실행할 쿼리의 <trim>문 안에 쿼리 가장 뒤에 붙여준다
prefixOverrides:실행할 쿼리의 <trim>문 안 조건( <if> )이 true이면 prefixOverrides=" "안에 들어있는 해당 문자들을 자동으로 지워준다
<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>
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<trim prefix="WHERE" prefixOverrides="AND|OR">
<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>
</trim>
</select>