
MyBatis基礎知識點:trim标簽的使用
作者:wt_better
來源 : https:// blog.csdn.net/wt_better /article/details/80992014
MyBatis的trim标簽一般用于去除sql語句中多餘的and關鍵字,逗号,或者給sql語句前拼接 “where“、“set“以及“values(“ 等字首,或者添加“)“等字尾,可用于選擇性插入、更新、删除或者條件查詢等操作。
以下是trim标簽中涉及到的屬性:
下面使用幾個例子來說明trim标簽的使用。
1、使用trim标簽去除多餘的and關鍵字
有這樣的一個例子:
<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’
你可以使用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>
trim标簽也可以完成相同的功能,寫法如下:
<trim prefix="WHERE" prefixOverrides="AND">
<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>
2、使用trim标簽去除多餘的逗号
有如下的例子:
如果紅框裡面的條件沒有比對上,sql語句會變成如下:
INSERT INTO role(role_name,) VALUES(roleName,)
插入将會失敗。
使用trim标簽可以解決此問題,隻需做少量的修改,如下所示:
其中最重要的屬性是
suffixOverrides=","
表示去除sql語句結尾多餘的逗号.
注:如果你有興趣的話,也可以研究下Mybatis逆向工程生成的Mapper檔案,其中也使用了trim标簽,但結合了foreach、choose等标簽,更多的是牽扯到Criterion的源碼研究。不過研究完之後,你将熟練掌握mybatis各種标簽的使用,學到Criterion的設計思想,對自己的啟發将會很大。