본문 바로가기
JAVA/MyBatis

mybatis - 동적SQL(if / choose / where / set / foreach)

by 설총이 2018. 9. 4.




1. if


1
2
3
4
5
6
7
8
9
10
11
12
<select id=”findActiveBlogLike” parameterType=”Blog” resultType=”Blog”>
 
SELECT * FROM BLOG WHERE state = ‘ACTIVE’ 
 
<if test=”title != null”> 
AND title like #{title} 
</if> 
 
<if test=”author != null and author.name != null”> 
AND author_name like #{author.name}
</if>
</select>
cs




2. choose


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<select id=”findActiveBlogLike”
parameterType=”Blog” 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>
 
cs





3. where


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
<select id=”findActiveBlogLike”
     parameterType=”Blog” 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>
cs


where 요소는 태그에 의해 컨텐츠가 리턴되면 단순히 “WHERE” 만을 추가한다.

게다가, 컨텐츠가 “AND” 나 “OR” 로 시작한다면, 

그 “AND” 나 “OR”를 지워버린다.



4. set


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<update id="updateAuthorIfNecessary" parameterType="domain.blog.Author"> 
 
update Author 
 
<set> 
    <if test="username != null">username=#{username},
    </if> 
    <if test="password != null">password=#{password},
    </if>
    <if test="email != null">email=#{email},
    </if>
    <if test="bio != null">bio=#{bio}
    </if>
</set> 
    where id=#{id}
</update>
cs


여기서 set 요소는 동적으로 SET 키워드를 붙히고, 필요없는 콤마를 제거한다.




5. foreach


1
2
3
4
5
6
7
8
9
10
<select id="selectPostIn" resultType="domain.blog.Post"> 
 
    SELECT * FROM POST P WHERE ID in 
 
<foreach item="item" index="index" collection="list" open="(" separator="," close=")"> 
 
    #{item} 
 
</foreach> 
</select>
cs




'JAVA > MyBatis' 카테고리의 다른 글

mybatis - <select>의 속성 / keyProperty / sql문에 null허용법  (2) 2018.09.04
mybatis 개념/순서  (0) 2018.09.04