Database

동적 SQL (ibatis)

소밍소밍 2022. 3. 15. 06:51

if

  • 동적 SQL에서 가장 공통적으로 사용되는 것
  • 여러 개를 사용할 수도 있다.
<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’
   <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>

choose - when, otherwise

  • 자바 switch와 비슷함 (case: when, 마지막: otherwise)
  • 얼핏 보면 when에 2개가 해당되면 2가지 조건이 추가될 것 같지만, choose 안에 들어있기 때문에 한가지만 골라 추가하게 된다.
<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>

where & trim

  • 내부에서 컨텐츠가 리턴되면 WHERE만 추가해 주고, 컨텐츠가 AND나 OR로 시작한다면 AND나 OR을 지운다
  • 만약 <where> 자리에 WHERE을 넣고, <if> 조건에 아무것도 해당되지 않는다면 WHERE 로 끝나는 쿼리를 만들게 되고, AND로 시작하는 두번째 이후 조건에만 맞다면 WHERE AND someCondition이 만들어지게 될 것이다. 이런 문제를 방지하기 위해 <where>을 사용하는 것
  • <trim>은 위와 같은 결과를 리턴하게 된다.
<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>
  
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

set & trim

  • UPDATE문에서 아래의 where처럼 사용하게 된다.
<update id="updateAuthorIfNecessary">
  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>
  
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

foreach

  • 열고 닫는 문자열 명시, 반복간에 둘 수 있는 구분자 추가 가능
  • Map, List, Set 등 반복가능한 객체 전달할 수 있다.
  • index: 몇 번째 반복인지 나타냄
  • value: 반복 과정에서 가져오는 요소. 아래 코드에서의 #{item}
  • Map을 사용할 때 index는 key가 되고, 항목은 value가 됨
<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>

출처

'Database' 카테고리의 다른 글

테이블 파티셔닝  (0) 2022.03.15
[작성중] DB 인덱스 (Index)  (0) 2022.03.15
iBATIS & MyBATIS  (0) 2022.03.15