MyBatis에서 기본적인 동적 SQL을 사용하는 예
<if>는 주어진 조건을 만족하는 경우, 주어진 절을 SQL문장에 포함한다
<select id=”findBook” parameterType=”Book” resultType=”Book”> SELECT * FROM book WHERE state = ‘ACTIVE’ <if test=”title != null”> AND title like '%'||#{title}||'%' </if> <if test=”author != null and author.name != null”> AND title like #{author.name} </if> </select>
<choose><when><otherwise> 은 여러개의 조건 중에서 조건을 만족하는 한개의 절만 SQL에 포함한다
<select id=”findBook” parameterType=”Book” resultType=”Book”> SELECT * FROM book WHERE state = ‘ACTIVE’ <choose> <when test=”title != null”> AND title like #{title} </when> <when test=”author != null and author.name != null”> AND title like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select>
<where> 는 SQL문장 중에 'where'가 필요하면 포함하고 아니면 제거한다
그리고 where절의 문법에 맞지않는 AND, OR 를 제거한다
<select id=”findBook” parameterType=”Book” resultType=”Book”> SELECT * FROM book <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 title like #{author.name} </if> </where> </select>
위의 경우, 모든 조건이 맞지 않으면 SQL문장에 'where'를 포함하지 않는다
위의 경우, 첫번째 조건이 맞지 않을 경우 두번째 혹은 세번째 절이 포함된다면 'AND'를 제거한다
<set>은 update 문장의 set절에서 문제가 되는 comma(,)를 해결해 준다
<update id="updateAuthorIfNecessary" parameterType="Author"> update Author <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email},</if> <if test="bio != null">bio=#{bio}</if> </set> where id=#{id} </update>
위의 경우 마지막 조건이 맞지 않으면 세번째 절의 콤마가 제거되어야 한다
문자열, 숫자, null 비교
<if test="str == null"> SQL </if> <if test="str != null"> SQL </if> <choose> <when test="str == null"> SQL </when> <otherwise> SQL </otherwise> </choose> <if test="str == ''"> SQL </if> <if test="str != ''"> SQL </if> <choose> <when test="str == ''"> SQL </when> <otherwise> SQL </otherwise> </choose> <if test='num > 10'> SQL </if> <if test='num >= 10'> SQL </if> <if test='num < 10'> SQL </if> <if test='num <= 10'> SQL </if> <if test='ename == "WARD"'> SQL </if> <if test='ename != "WARD"'> SQL </if> <if test='ename != null and ename != ""'> SQL </if>
SQL 문장에 포함된 <, >가 XML 문법 오류를 발생하는 경우에는 다음과 같이 CDATA 섹션으로 처리한다
XML 문법에서 CDATA 는 Character Data 의 의미를 가지며 해당 섹션에는 문자 데이터만 있고 태그는 없다는 표현이다
SELECT * FROM emp WHERE deptno = #{deptno} <if test='ename != null'> <![CDATA[ AND ename <= #{ename} ]]> </if> SELECT * FROM emp WHERE deptno = #{deptno} <if test='ename != null'> AND ename <= #{ename} </if>