[MYBATIS] choose 절을 이용한 DynamicSQL

류동재·2022년 3월 3일
0

MyBatis에서 choose 절을 활용한 동적 쿼리를 작성할 수 있다. 보통 특정 조건에 따라 쿼리의 형태가 다이나믹해지므로 MyBatis에서 많이 사용되는 방법으로 절이 있다.

<choose></choose>,<when></when>,<otherwise></otherwise>

우선 위 세가지 종류를 사용한다.

select *
from table1
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>
		<when test="a != null and a == 3">and a = 3</when>
    <otherwise>
        and a is not null
    </otherwise>
</choose>

전체 choose 조건문의 범위를 결정하는 태그를 시작으로 의 검증부분을 통해 조건을 건다. a 라는 변수는 자바 Interface Mapper에서 넘어온 파라미터 그대로 사용할 수 있다.

태그는 else랑 비슷한 느낌이지만, 떄로는 default의 의미로 사용될 수 있다. 위 쿼리처럼 존재하는지 여부만 확인할 경우 default값을 is not null로 설정할 수도 있다.

그리고 mybatis의 특징으로 태그의 내부는 모든 태그가 들어올 수 있다. 또, 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>
        and a is not null
    </otherwise>
</choose>

0개의 댓글