Develope/DataBase

[ORACLE] 동적 WHERE 쿼리 (trim prefix="WHERE" prefixOverrides="AND |OR ")

고로이 2018. 12. 26. 15:20
반응형


나는 주로


WHERE 1=1


을 쓴다


이런 방법도 있었군..





출처 : http://cocomo.tistory.com/250



여러 구문 중 하나만 실행

<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>
</select>

 - 위 구문은 잘못 사용된 예

 - 만약 아무런 파라미터도 없다면 아래와 같은 쿼리가 만들어진다.

SELECT *

FROM BLOG 

WHERE

 - 두 번째 조건만 해당된다면 아래와 같은 쿼리가 만들어짐

SELECT *

FROM BLOG 

WHERE    

AND title like someTitle

 - 모두 실행할 수 없는 쿼리가 만들어짐.

 - 때문에 trim을 사용해야 함

<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>


<where> </where> 는 내부에 컨텐츠가 존재할 때 where 키워드를 포함

 - 그렇지 않는 경우는 where 키워드를 쓰지 않음

 - 또한 where 다음 AND 혹은 OR 가 바로 올 경우 AND, OR 키워드를 삭제 시킨다.

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

 - 혹은 위 구문과 같이 trim을 바로 사용할 수도 있다.

<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG <trim prefix="WHERE" prefixOverrides="AND |OR ">

<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> </trim> </select>


<set> </set> 는 내부에 컨텐츠가 존재할 때 set 키워드를 포함시킴

 - 그렇지 않는 경우는 set 키워드를 쓰지 않음

 - 또한 set 다음 콤마( , ) 가 바로 올 경우 콤마( , )를 삭제 시킨다.

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

 - 혹은 위 구문과 같이 trim을 바로 사용할 수도 있다.

<update id="updateAuthorIfNecessary"> update Author <trim prefix="SET" suffixOverrides=",">
<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> </trim> where id=#{id} </update>



출처: http://cocomo.tistory.com/250 [Cocomo Coding]

반응형