[Mybatis] choose절을 이용한 Dynamic SQL 구현 (choose, when, otherwise)

안녕하세요. 오늘은 MyBatis에서 choose 절을 활용한 동적쿼리를 만드는 방법들에 대해서 소개해보려고 합니다.

 

보통 특정 조건에 따라 쿼리의 형태가 다이나믹해지도록 구성하기 위한 방법으로 많이 사용되는 <choose> 절입니다.

 

사용되는 xml 태그는 <choose></choose>,<when></when>, <otherwise></otherwise> 세가지 종류입니다.

 

하나씩 살펴보겠습니다.

 


구조 및 사용법

select *
from tableA
where deleted = false
<choose>
    <when test="a != null and a == 1">
    	and a = 1
    </when>
    <when test="a != null and a == 2">
    	and a = 2
    </when>
    <otherwise>
    	<!-- 기본조건 여기서는 not null 로 잡았다. -->
        and a is not null
    </otherwise>
</choose>

전체 choose 조건문의 범위를 결정하는 <choose> 태그를 시작으로 <when>test 속성을 통해 조건을 건다.

a 라는 변수는 자바 Interface Mapper에서 넘어온 파라미터를 그대로 사용할 수 있다.

<otherwise> 태그는 "그 외에는" 이라는 느낌인데, 때로는 default의 의미로 사용될 수 있다. 예컨데 위의 예시처럼 a 컬럼의 값이 존재하는지만 판단하고자 할 때 default 조건처럼 a is not null을 걸 수 있을 것이다.

 


 

공통된 mybatis의 특징이지만 <when> 태그의 내부는 모든 태그가 들어올 수 있다. 예컨데 when 절안에 if 절로 좀더 세분화가 가능하고, foreach 절을 사용해서 loop를 돌릴 수도 있다.

select *
from tableA
where deleted = false
<choose>
    <when test="a != null and a.length > 0">
    	and a in <foreach item="a" collection="a_list" open="(" seperate="," close=")">#{a}</foreach>
    </when>
    <otherwise>
    	<!-- 기본조건 여기서는 not null 로 잡았다. -->
        and a is not null
    </otherwise>
</choose>

 

또한 별로 사용성은 없지만 test 속성 내에서는 자바 코드가 동작하기도 합니다.

select *
from tableA
where deleted = false
<choose>
    <when test="keyword.equalsIgnoreCase('ALL')">
    	keyword = 'all'
    </when>
    <otherwise>
    	<!-- 기본조건 여기서는 not null 로 잡았다. -->
        and a is not null
    </otherwise>
</choose>

 

댓글

Designed by JB FACTORY