天天看點

MyBatis 動态 SQL trim 的應用,可以添加或删除字首或字尾

版權聲明:本文為 testcs_dn(微wx笑) 原創文章,非商用自由轉載-保持署名-注明出處,謝謝。 https://blog.csdn.net/testcs_dn/article/details/80986793

MyBatis 動态 SQL trim 的應用,可以添加或删除字首或字尾。

比如:你的查詢需求是有一部分字段條件是 and 關系,而有一部分字段是 or 關系,例如:

Select * from tableName where 
a=1 and b=2 and c=3
and(
   d like '%a%' or e like '%b%'
)           

那麼 Where 的部分可以使用 Where 的功能,這樣寫:

<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 條件中包含 if 條件語句,也就是可能存在根本沒有條件的可能,那麼使用 <where> 标簽,就能夠實作如果沒有任何條件的話,就不添加 Where 關鍵詞的功能;同時還可以将條件語句中存在的第一個 AND 去掉。

但是遇到有一部分字段是 or 關系的情況怎麼辦呢?

<trim> 就能實作這樣一個神奇的功能!

先看幾個官方的例子:

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

這個就可以代碼上面的  <where> 标簽的功能,使用方法就是用它來代替  <where> 标簽。

再看看代替 <set> 标簽的方法:

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <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>
    </set>
  where id=#{id}
</update>           

代替方法:

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

嗯嗯,它的用法你是不是已經學會了呢?

講重點:

<trim> 标簽屬性:prefix 要添加的字首,suffix 要添加的字尾,prefixOverrides 要去掉的語句前面部分的内容,suffixOverrides 要去掉的語句後面部分的内容。

需求實作方法:

<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>
    <trim prefix="AND (" suffix=")" prefixOverrides="OR ">
     <if test="title != null">
        OR title like #{title}
    </if>
    <if test="author != null and author.name != null">
        OR author_name like #{author.name}
    </if>
    </trim>
  </where>
</select>           

你看懂了嗎?

官方文檔隻是給了簡單的例子,标簽都有哪些屬性也沒有全部列出來。

學習的時候還要連蒙帶猜的。