Mybatics動態sql

福麓呼嚕發表於2020-10-01

Mybatics動態sql

if語句

只有滿足在test中的條件的情況下,才會在查詢條件中加入if標籤內的內容

<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

test中需要包含兩個條件的情況下(直接使用and)

<if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>

choose、when、otherwise

想從多個條件中選擇一個使用。針對這種情況,MyBatis 提供了 choose 元素,類似Java 中的 switch 語句:

<select id="findActiveBlogLike"
     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>

這裡的when相當於case語句,otherwise就相當於switch中的default語句。

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

這種情況下一旦遇到第一個條件不滿足,下面某個條件滿足就會出現查詢條件第一個子條件出現and字首:如:

SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’

這樣的語句很明顯會造成程式執行錯誤。
這時就可以使用trim標籤,將上述程式碼改為:

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE
 **<trim prefix="WHERE" prefixoverride="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>

prefix:字首      
prefixoverride:去掉第一個and或者是or
有了這個標籤,就很容易解決了子條件出現字首的問題

foreach

<delete id="deleteBatch"> 
    delete from user where id in
    <foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
      #{id}
    </foreach>
  </delete>

假如 ids = {1,2,3,4,5}
這裡的sql就相當於:

delete form user where id in (1,2,3,4,5)

相關文章