mybatis的trim

建議先查看官方文檔:mybatis

我們經常會在mybatis操作中用到where和<if></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>

如果這些條件沒有一個能匹配上會發生什麼?最終這條 SQL 會變成這樣:

SELECT * FROM BLOG
WHERE

這會導致查詢失敗。如果僅僅第二個條件匹配又會怎樣?這條 SQL 最終會是這樣:

SELECT * FROM BLOG
WHERE 
AND title like ‘someTitle’

 這也是一條錯誤的語句,多了一個AND。

MyBatis 有一個簡單的處理,這在 90% 的情況下都會有用。而在不能使用的地方,你可以自定義處理方式來令其正常工作。一處簡單的修改就能達到目的,用<where></where>標籤:<where> 元素只會在至少有一個子元素的條件返回 SQL 子句的情況下才去插入“WHERE”子句。而且,若語句的開頭爲“AND”或“OR”,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>標籤沒有生效怎麼辦?這個時候就引入了<trim>的概念

<trim>是什麼?

trim的英文名是修剪、整理的意思。正如它的英文名所譯,對SQL語句進行修剪,即添加前綴(後綴)或者去除掉多餘的前綴(後綴)。

<trim>的使用:

prefixOverrides 屬性會忽略通過管道分隔的文本序列(注意此例中的空格也是必要的)。它的作用是移除所有指定在 prefixOverrides 屬性中的內容,並且插入 prefix 屬性中指定的內容。

prefix:前綴

prefixoverride:去掉第一個and或者是or

suffixOverrides:去掉最後一個XXX

舉個例子一:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ... 
</trim>
select * from user 

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

    <if test="name != null and name.length()>0"> AND name=#{name}</if>

    <if test="gender != null and gender.length()>0"> AND gender=#{gender}</if>

  </trim>

等同於,下面的語句(自動在前面添加where,去除掉第一個AND或者OR)

select * from user 
where 
    name = 'xx' 
and 
    gender = 'xx'

舉個例子二:

<trim prefix="SET" suffixOverrides=",">
  ...
</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>

等同於,下面的語句(set 元素會動態前置 SET 關鍵字,同時也會刪掉無關的逗號,因爲用了條件語句之後很可能就會在生成的 SQL 語句的後面留下這些逗號。)

<update id="updateAuthorIfNecessary">
  update Author
    set
      username=#{username},
      password=#{password},
      email=#{email},
      bio=#{bio}
  where id=#{id}
</update>

歡迎加入 CSDN技術交流羣:(點擊即可加羣)QQ羣:681223095。

因經常有人留言,未能及時查看到和回覆,所以特建此羣,以方便交流。方便問題討論,有問題和沒有問題的小夥伴均可加入,用作自我學習和共同進步。本博主不一定長期在線,但是qq羣裏會有很多熱心的小夥伴,大家一起討論解決問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章