MyBatis - <choose>, <when>, <otherwise> 태그
<choose>, <when>, <otherwise> 태그
<choose>, <when>, <otherwise>의 이해
<if> 태그의 경우 조건식이 참인 모든 <if> 태그 내 쿼리문이 실행된다. 반면에, <choose> 태그 같은 경우 조건식이 참인 <when> 태그를 찾으면 해당 태그의 쿼리문만 실행한다. 다시 말해 조건식을 가진 여러 개의 <when> 태그 중 오로지 한 개의 <when> 태그 내 쿼리문을 실행하는 것이다. 대부분의 프로그래밍 언어에서 사용되는 if-else if 절과 비슷한 역할을 수행한다.
<choose>
<when test="조건식01"> 쿼리문01 </when>
<when test="조건식02"> 쿼리문02 </when>
<when test="조건식03"> 쿼리문03 </when>
<when test="조건식04"> 쿼리문04 </when>
<otherwise> 쿼리문05 </otherwise>
</choose>
<choose> 태그 안에서 <when> 태그와 <otherwise>를 작성한다. <when> 태그는 각각 test 속성을 가지며 해당 속성 안에 조건식을 작성한다. 태그가 실행되면 <when> 태그의 조건식을 순서대로 확인하여 참을 반환하는 <when> 태그 내 쿼리문을 실행하게 된다.
만약 <when> 태그의 조건식 중 참을 반환하는 것이 없을 경우 <otherwise> 태그 내에 작성된 쿼리문이 실행된다. 추가적으로, <otherwise> 태그는 생략이 가능하다.
<choose>, <when>, <otherwise>의 활용
<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>
위 코드는 MyBatis 공식 홈페이지의 <if> 태그 예제에 대한 코드이다.
<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>
</choose>
</if>
</select>
위 코드는 <choose>, <when> 태그를 사용한 똑같은 예제이다.
똑같은 역할을 수행하는 코드처럼 보이지만, 결과는 확연하게 다르다. 첫 번째 <if> 태그를 사용한 예제의 경우 <if> 태그 조건식이 둘 다 참이면 <if> 태그가 가지고 있는 쿼리문을 두 개 모두 실행한다. 하지만, <choose>, <when> 예제의 경우 <when> 태그의 조건식이 참이라면 다음 <when> 태그의 조건식을 탐색하지 않고 단 하나의 쿼리문만 실행하게 된다.