java <trim prefix="where" prefixoverrides="and">

길위에 히피·2024년 1월 23일

Spring

목록 보기
2/6

MyBatis의 요소는 동적 SQL 쿼리 생성 시 WHERE 절과 같은 조건절을 다룰 때 매우 유용한 도구입니다. 이를 통해 불필요한 조건을 쉽게 추가하거나 제거할 수 있어 더 유연한 SQL 쿼리를 작성할 수 있습니다.

아래와 같이 if 조건문을 활용해서 구문을 생성할수 있습니다.

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

다만 이럴경우 앞에 state문이 없을 경우 오류가 발생합니다. 그래서 이렇게 조건문을 사용하는 것보다 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>  
profile
마음맘은 히피인 일꾼러

0개의 댓글