Database

[MyBatis] 동적쿼리, 기타 문법

HSRyuuu 2023. 5. 15. 13:37

동적 SQL

MyBatis를 사용하는 이유는 편리한 동적 SQL 기능 때문이다. 동적 쿼리를 위해 제공되는 기능은 아래와 같다.

  • if
  • choose(when, otherwise)
  • where
  • foreach
MyBatis 공식 매뉴얼: https://mybatis.org/mybatis-3/ko/index.html
MyBatis 스프링 공식 매뉴얼: https://mybatis.org/spring/ko/index.html

if

단순한 if 문이다.

if문의 test 조건에 만족하면 해당 SQL문을 추가한다.

<select id="findActiveBlogWithTitleLike" resultType="Blog">
 SELECT * FROM BLOG
 WHERE state = ‘ACTIVE’
 <if test="title != null">
	 AND title like #{title}
 </if>
</select>

choose - when, otherwise

자바의 switch 구문과 비슷하다.

  • switch - choose
  • case - when
  • default - 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>

where

WHERE문을 동적으로 추가해준다.

  • 만약 SELECT * FROM BLOG 구문 이후로 if문을 하나도 만족하지 않게 되면 아무것도 추가하지 않는다.
  • if문을 만족하면 WHERE 구문 이후에 <if> 내의 SQL을 추가해 준다.
  • 만약 if문을 만족하는 부분이 있는데, 그 SQL이 AND로 시작한다면 첫 번째 AND를 WHERE로 바꿔준다.
<select id="findActiveBlogLike" resultType="Blog">
 SELECT * FROM BLOG
 
 <where>
   <if test="state != null">
 	state = #{state}
   </if>
   <if test="title != null">
 	AND title like #{title}
   </if>
   <if test="author != null and author.name != null">
	 AND author_name like #{author.name}
   </if>
 </where>
 
</select>

foreach

컬렉션을 반복 처리할 때 사용한다.

파라미터로 List를 전달하면 된다.

<select id="selectPostIn" resultType="domain.blog.Post">
 SELECT * FROM POST P
 <where>
   <foreach item="item" index="index" collection="list" open="ID in (" 
       	 	separator="," close=")" nullable="true">
 	#{item}
   </foreach>
 </where>
</select>

컬렉션 List에 1,2,3,4,5가 주어진다면,

 SELECT * FROM POST P

     WHERE ID in (1,2,3,4,5);

 SQL이 작성된다.


 

애노테이션으로 직접 SQL 작성

XML 대신 애노테이션으로 직접 SQL을 작성할 수 있다.

@Insert, @Update, @Delete, @Select 4가지 애노테이션을 사용할 수 있다.

간단한 SQL을 작성할 때 사용한다.

@Select("select id, item_name, price, quantity from item where id=#{id}")
Optional<Item> findById(Long id);

특수문자 사용

xml은 html처럼 < , >를 태그로 사용한다. 따라서 대소 비교를 위한 부등호는 특수 기호를 사용해야 한다.

< : &lt;
> : &gt;
& : &amp;

XML CDATA 사용

XML에서는 부등호, & 기호를 그대로 사용하기 위해 CDATA 문법을 사용한다. 이 구문 안에서는 부등호 등이 단순 문자로 인식된다.

<![CDATA[ /*코드*/ ]]>
<where>
	 <if test="itemName != null and itemName != ''">
 	and item_name like concat('%',#{itemName},'%')
 	</if>
 
 	<if test="maxPrice != null">
 		<![CDATA[
 		and price <= #{maxPrice}
 		]]>
 	</if>
 </where>

 


(참고) 인프런 - 김영한님 스프링 DB
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-db-2/dashboard
반응형