mybatis

동적 SQL

안녕로봇 2017. 3. 29. 19:45

동적 SQL

- SQL문에서 여러가지 분기처리를 위한 작업

- 파라미터 타입은 Map이나 클래스(VO, DTO 같은...)로 설정해야 한다!!


if 엘리먼트

 ex)

<select id="selectCommentByCondition" parameterType="hashmap" resultType="Comment">

SELECT comment_no, user_id, comment_content, reg_date FROM comment2

<if test="commentNo != null">

WHERE comment_no = #{commentNo} <--! 이때 commentNo는 해쉬맵의 키이고 해당하는 값을 가져옴-->

</if>

</select>


choose(when, otherwise) 엘리먼트

 ex)

<select id="selectCommentByConditionChoose" parameterType="hashmap" resultType="Comment">

SELECT comment_no, user_id, comment_content, reg_date

FROM comment2

<choose>

<when test="commentNo != null">

WHERE comment_no = #{commentNo}

</when>

<when test="user != null and user.userId != null">

WHERE user_id = #{user.userId}

</when>

<otherwise>

WHERE comment_no = 1

AND user_id = 'fromm0'

</otherwise>

</choose>

</select>


trim 엘리먼트

구문이 꼬이는걸 방지시켜준다 - (if문으로 쓸경우 where가 두번 나오거나 마지막 부분에 ,가 찍히는등)

where을 붙여주거나 AND, OR을 지워주거나 등등

ex)

<select id="selectCommentByConditionIf" parameterType="hashmap" resultType="Comment">

SELECT comment_no, user_id, comment_content, reg_date

FROM comment2

<where>

<if test="commentNo != null">

comment_no = #{commentNo}

</if>

<if test="user != null and user.userId != null">

AND user_id = #{user.userId}        ->> 앞쪽 if문이 null값인 경우 AND는 사라지고 where가 붙음

</if>

</where>

</select>


또는


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

<if test="commentNo != null">

AND comment_no = #{commentNo}

</if>

<if test="user != null and user.userId != null">

AND user_id = #{user.userId}

</if>

</trim>



trim 엘리먼트가 제공하는 속성

- prefix: 처리 후 엘리먼트 내용이 있으면 가장 앞에 붙여준다 (where같은거)

- prefixOverrides: 처리후 엘리먼트 내용 가장 앞에 해당 문자가 있다면 지워줌 (and 등)

- suffix: 처리 후 엘리먼트 내용이 있으면 가장 뒤에 붙여줌 (콤마같은거)

- suffixOverrides: 처리후 엘리먼트 내용 가장뒤에 해당문자가 있으면 지워줌 (콤마 같은거)


ex)

UPDATE comment2

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

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

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

</trim>

WHERE comment_no = #{commentNo};


foreach 엘리먼트

ex)

long[] cmtNos={1L,2L,3L};

HashMap<String,Object> hmap= new HashMap<String,Object>();

hmap.put(“commentNos”, cmtNos);


<select id="selectCommentByConditionForeach" parameterType="hashmap" resultType="Comment">

SELECT comment_no, user_id, comment_content, reg_date

FROM comment2

<trim prefix="WHERE" prefixOverrides="AND |OR "> <--! 빠져도 되는게 아닌지?? -->

<if test="commentNos != null">

comment_no IN

<foreach collection="commentNos" item="commentNo"

index="index" open="(" close=")" separator=",">

#{commentNo}

</foreach>

</if>

</trim>

</select>


=> 완성된 구문

SELECT comment_no, user_id, comment_content, reg_date

FROM comment2

WHERE comment_no IN (1, 2, 3)