반응형
IF 문 : 특정 조건을 만족 할때 동작하는 쿼리
<select id="findActiveBlogByTitle" resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
위의 경우는 title이 있는 경우에만 title에 대한 검색조건을 추가하는 쿼리
조금 응용을 하면 다음과 같이 사용가능
<select id="findActiveBlogWithTitleLike" resultType="Blog">
SELECT * FROM BLOG
WHERE 1 = 1
<if test="state != null">
AND state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="searchStartDate != '' and searchStartDate != null">
AND DATE_FORMAT(CREATE_DATE, '%Y-%m-%d') <![CDATA[>=]]> #{searchStartDate}
</if>
<if test="searchEndDate != '' and searchEndDate != null">
AND DATE_FORMAT(CREATE_DATE, '%Y-%m-%d') <![CDATA[<=]]> #{searchEndDate}
</if>
</select>
상황에 맞게 조합되는 조건으로 SELECT가 가능하게 쿼리를 짤 수 있음
CHOOSE, WHEN, OTHERWISE : Switch문 혹은 If-else문을 표현하는 방법
title이 있는 경우 title의 조건을 조회하고, author의 name이 있는 경우 author.name을 조건으로 조회
title과 author.name 두가지 모두가 없을 경우에는 otherwise의 featured 조건을 사용하여 조회입니다.
<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>
반응형
'Backend > DB 실무' 카테고리의 다른 글
[Mybatis] 반복문 및 bind (0) | 2024.02.26 |
---|---|
[Mybatis] WHERE을 조금 더 편하게 사용하기 (0) | 2024.02.26 |
[H2] H2 SQL파일 로드 (0) | 2024.02.26 |
[Mybatis] Mybatis VS JPA (0) | 2024.02.20 |
Insert문 (0) | 2024.02.19 |