[ MyBatis3 ] 동적 SQL

- MyBatis 의 가장 강력한 기능 중 하나는 동적 SQL 기능이다.

- MyBatis 다른 요소의 사용을 최대한 제거하기 위해 OGNL기반의 표현식을 가져왔다.

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

* if

<select id = "aaaa" parameterType = "Blog" resultType = "Blog">

SELECT * FROM BLOG

WHERE state = "bbbb"

<if test="title != null">

AND title like #{title}

</if>

</select>


- 이 구문은 선택적으로 문자열 검색 기능을 제공한다.

- title 값이 없다면 모든 active상태의 Blog가 리턴될 것이고 title 값이 있다면 그 값과 비슷한 데이터를 찾게 될 것이다.

* choose, when , otherwise

- 종종 모든 조건을 원하는 대신 한가지 경우만 만족하는 경우를 원할 수 있다, 자바에서 swith문과 유사하다.

<select id = "aaa" parameterType ="Blog" 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>


- title 만으로 검색하고 author 가 있으면 그값으로 검색하고 둘다 제공하기 않는다면 featured 상태의 blog가 리턴된다.


* trim, where, set


위 예제에서 어떤 조건에도 해당하지 않는다면

SELECT * FROM BLOG

WHERE

처럼 나온것이고 sql문이 꼬이게 될 것이다.

<select id=”findActiveBlogLike”parameterType=”Blog” 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 title like #{author.name}

</if>

</where>

</select>

>> where 요소는 태그에 의해 컨텐츠가 리턴되면 필요할 경우 "WHERE" 을 추가한다.

만약 컨텐츠가 "AND" 나 "OR"로 시작한다면 삭제해버린다.


만약 where 요소가 기대처럼 동작을 하지 않는다면, trim 요소를 사용자 정의할 수 있다.


<trim prefix ="WHERE" prefixOverrides = "AND | OR">

</trim>

>> override 속성은 오버라이드하는 텍스트의 목록을 제한한다.

결과는 override 속성에 명시된 것들을 지우고 with 속성에 명시된 것을 추가한다.


<update id ="updateAuthorIfNecessary" parameterType="domain.blog.Author">

update Author

<set>

<if test="username != null">username=#{username},</if>

<if test="password != null">password=#{password},</if>

<if test="bio != null">bio=#{bio}</if>

</set>

where id = #{id}

</update>


>> 여기서 set 요소는 동적으로 SET 키워드를 붙이고 필요없는 콤마를 제거한다.

<trim prefix="SET" suffixOverrides=",">

</trim>


* foreach


- 동적 SQL에서 공통적으로 필요한 것으 collection에 대한 반복처리를 하는 것이다. 종종 IN 조건을 사용하게 된다.

- foreach 요소는 매우 강력하고 collection을 명시하는 것을 허용한다.

- 요소내부에서 사용할 수 있는 item, index 두가지 변수를 선언한다.


- 열고 닫는 문자열로 명시할 수 있고 반복간에 둘 수 있는 구분자도 추가할 수 있다.