MyBatis 3 動態(tài)SQL-if

2022-04-11 10:21 更新

if

使用動態(tài) SQL 最常見情景是根據(jù)條件包含 ?where ?子句的一部分。比如:

<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

這條語句提供了可選的查找文本功能。如果不傳入 “?title?”,那么所有處于 “?ACTIVE?” 狀態(tài)的 ?BLOG ?都會返回;如果傳入了 “?title?” 參數(shù),那么就會對 “?title?” 一列進行模糊查找并返回對應的 ?BLOG ?結果(細心的讀者可能會發(fā)現(xiàn),“?title?” 的參數(shù)值需要包含查找掩碼或通配符字符)。

如果希望通過 “?title?” 和 “?author?” 兩個參數(shù)進行可選搜索該怎么辦呢?首先,我想先將語句名稱修改成更名副其實的名稱;接下來,只需要加入另一個條件即可。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <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>


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號