點擊上方藍色「程序猿DD」,選擇「設為星標」
回復「資源」獲取獨家整理的學習資料!
作者 | wt_better
<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 會變成這樣:這會導致查詢失敗。如果僅僅第二個條件匹配又會怎樣?這條 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 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標籤可以解決此問題,只需做少量的修改,如下所示:註:如果你有興趣的話,也可以研究下Mybatis逆向工程生成的Mapper文件,其中也使用了trim標籤,但結合了foreach、choose等標籤,更多的是牽扯到Criterion的源碼研究。不過研究完之後,你將熟練掌握mybatis各種標籤的使用,學到Criterion的設計思想,對自己的啟發將會很大。如果想要了解更多關餘trim標籤的內容,請移步《trim標籤源碼解析》。本文參考 Mybatis官方文檔(https://mybatis.org/mybatis-3/zh/dynamic-sql.html)歡迎加入我的知識星球,聊聊技術、說說職場、扯扯社會。
【技術圈】關於Consul作為註冊中心的四種形態演變【技術圈】配置中心除了存儲應用配置之外,適合做其他配置的存儲嗎?【社會人】老實工作沒有其他收入,為什麼還要補繳個稅?【社會人】除了年終彙算清繳之外,今年的另一件大事:LPR加入方式:長按下方二維碼噢
我的星球是否適合你?
點擊閱讀原文看看我們都在聊啥