mybatis的trim標籤一般用於去除sql語句中多餘的and關鍵字,逗號,或者給sql語句前拼接 「where「、「set「以及「values(「 等前綴,或者添加「)「等後綴,可用於選擇性插入、更新、刪除或者條件查詢等操作。
以下是trim標籤中涉及到的屬性:
下面使用幾個例子來說明trim標籤的使用。
有這樣的一個例子:
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE <if test="state != null"> state = </if> <if test="title != null"> AND title like </if> <if test="author != null and author.name != null"> AND author_name like </if></select>如果這些條件沒有一個能匹配上會發生什麼?最終這條 SQL 會變成這樣:
這會導致查詢失敗。如果僅僅第二個條件匹配又會怎樣?這條 SQL 最終會是這樣:
SELECT * FROM BLOGWHERE 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 = </if> <if test="title != null"> AND title like </if> <if test="author != null and author.name != null"> AND author_name like </if> </where></select>trim標籤也可以完成相同的功能,寫法如下:
<trim prefix="WHERE" prefixOverrides="AND"> <if test="state != null"> state = </if> <if test="title != null"> AND title like </if> <if test="author != null and author.name != null"> AND author_name like </if></trim>
2、使用trim標籤去除多餘的逗號
有如下的例子:
如果紅框裡面的條件沒有匹配上,sql語句會變成如下:
INSERT INTO role(role_name,) VALUES(roleName,)插入將會失敗。使用trim標籤可以解決此問題,只需做少量的修改,如下所示:
其中最重要的屬性是
表示去除sql語句結尾多餘的逗號
註:如果你有興趣的話,也可以研究下Mybatis逆向工程生成的Mapper文件,其中也使用了trim標籤,但結合了foreach、choose等標籤,更多的是牽扯到Criterion的源碼研究。不過研究完之後,你將熟練掌握mybatis各種標籤的使用,學到Criterion的設計思想,對自己的啟發將會很大。
# 本文參考
Mybatis官方文檔(https://mybatis.org/mybatis-3/zh/dynamic-sql.html)
來源:https://blog.csdn.net/wt_better/article/details/80992014