공부 etc.

[Mybatis] <choose>, <when>, <otherwise> 그리고 <if>

꿈꾸는야오옹 2023. 5. 9. 16:30

조건식이 참인 경우 쿼리문을 실행하는 것들

 

차이점

true를 반환하는 <when>태그를 찾으면 거기서 멈춤, 여러개의 <when>태그는 오로지 한개의 <when>태그내부 쿼리만 실행.

만약 <when>태그의 조건식중 true 반환한 것이 없다면, <otherwise> 태그 내에 작성된 쿼리문이 실행. <otherwise>태그는 생략 가능

 

 

<if> 문 적용시

<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> 이용하면 아래와 같다.

<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>

 

참고

https://mybatis.org/mybatis-3/ko/sqlmap-xml.html