Dynamic SQL

1. MyBatis 동적 SQL

DynamicSQL

  • 검색 조건에 따라 SQL문이 달라지기 떄문에 이를 처리하기 위해 사용

MyBatis의 표현식

  • if
  • trim(where, set)
  • choose(when otherwise)
  • foreach

동적 SQL 작성 시 유의사항

  • MyBatis 구문을 이용하여 SQL문이 실행 시에 변경되기 떄문에 모든 케이스에 대해 테스트가 이루어져야 함
  • 동적 SQL문이 없는 상태에서 정삭적인 실행을 확인 후, 동적 SQL을 추가하여 개발

if

<select id="selectArticleById" resultType="kr.co.company.hello.vo.Article" parameterType="string">
    select  article_id as articleId, 
            author, 
            title, 
            content
    from 	article
    where	1=1
    <if test="articleId != null">
	    and	article_id = #{articleId}
    </if>
    <if test="author.name != null">
	    and	author = #{author.name}
    </if>
</select>
  • 파라미터 타입 안에 다른 타입(클래스)가 포함되어 캡슐화를 이룰 경우 .(dot) 연산자로 접근할 수 있다

choose(when otherwise)

<select id="selectArticleById" resultType="kr.co.company.hello.vo.Article" parameterType="string">
    select  article_id as articleId, 
            author, 
            title, 
            content
    from 	article
    <choose>
        <when test="articleId != null">
            where	article_id = #{articleId}
        </when>
        <when test="author.name != null">
            where	author = #{author.name}
        </when>
        <otherwise>
            where	title like #{title}
        </otherwise>
    </choose>
</select>
  • 여러 구문 중 하나만 실행된다

trim(where)

<select id="selectArticleById" resultType="kr.co.company.hello.vo.Article" parameterType="string">
    select  article_id as articleId, 
            author, 
            title, 
            content
    from 	article
    <trim prefix="WHERE" prefixOverrids="AND">
        <if test="articleId != null">
            article_id = #{articleId}
        </if>
        <if test="author.name != null">
            author = #{author.name}
        </if>
    </trim>
</select>
  • <where></where>는 내부에 컨텐츠가 존재할 때 where 키워드를 포함시킨다
  • trim을 이용해 일부 검색 조건이 존재하지 않을 때에 유연하게 대처할 수 있다

trim(set)

<update id="exampleUpdate">
	update	exampleTable
    <trim prefix="SET" suffixOverrids=",">
    	<if test="id != null">
            id = #{id}
        </if>
        <if test="name != null">
            name = #{name}
        </if>
        <if test="age != null">
            age = #{age}
        </if>
    </trim>
</update>
  • <set></set>은 내부에 컨텐츠가 존재할 떄 set 키워드를 포함시킨다
  • trim을 이용해 업데이트 시키는 컬럼이 불규칙할 때 유연하게 대처할 수 있다

foreach

<select id="selectArticleById" resultType="kr.co.company.hello.vo.Article" parameterType="string">
    select  article_id as articleId, 
            author, 
            title, 
            content
    from 	article
    where	article_id in
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
    	#{item}
    </foreach>
</select>
  • Dynamic Query에서 공통적으로 필요한 기능은 Collection의 반복 처리 기능
  • IN 키워드를 사용할 때 종종 사용된다
  • collection 속성은 List일 경우 list, array가 사용된다
  • 파라미터가 List일 경우 list, 파라미터가 Array(배열)일 경우 array를 사용한다