在 MyBatis 中除了使用 if+where 實(shí)現(xiàn)多條件查詢,還有一個(gè)更為靈活的元素 trim 能夠替代之前的做法。
trim 一般用于去除 SQL 語句中多余的 AND 關(guān)鍵字、逗號(hào),或者給 SQL 語句前拼接 where、set 等后綴,可用于選擇性插入、更新、刪除或者條件查詢等操作。trim 語法格式如下。
<trim prefix="前綴" suffix="后綴" prefixOverrides="忽略前綴字符" suffixOverrides="忽略后綴字符">
SQL語句
</trim>
trim 中屬性說明如下。
| 屬性 | 描述 |
|---|---|
| prefix | 給SQL語句拼接的前綴,為 trim 包含的內(nèi)容加上前綴 |
| suffix | 給SQL語句拼接的后綴,為 trim 包含的內(nèi)容加上后綴 |
| prefixOverrides | 去除 SQL 語句前面的關(guān)鍵字或字符,該關(guān)鍵字或者字符由 prefixOverrides 屬性指定。 |
| suffixOverrides | 去除 SQL 語句后面的關(guān)鍵字或者字符,該關(guān)鍵字或者字符由 suffixOverrides 屬性指定。 |
本節(jié)示例基于《第一個(gè)MyBatis程序》一節(jié)的代碼實(shí)現(xiàn)。
下面我們利用 trim 實(shí)現(xiàn)與 where 元素相同的效果。
要求:根據(jù)網(wǎng)站名稱或網(wǎng)址對(duì)網(wǎng)站進(jìn)行模糊查詢。
WebsiteMapper.xml 代碼如下。
<select id="selectWebsite" resultType="net.biancheng.po.Website">
SELECT id,name,url,age,country
FROM website
<trim prefix="where" prefixOverrides="and">
<if test="name != null and name !=''">
AND name LIKE CONCAT ('%',#{name},'%')
</if>
<if test="url!= null">
AND url like concat ('%',#{url},'%')
</if>
</trim>
</select>
WebsiteMapper 類中方法如下。
public List<Website> selectWebsite(Website website);
測試代碼如下。
public class Test {
public static void main(String[] args) throws IOException {
// 讀取配置文件mybatis-config.xml
InputStream config = Resources.getResourceAsStream("mybatis-config.xml"); // 根據(jù)配置文件構(gòu)建
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
// 通過SqlSessionFactory創(chuàng)建SqlSession
SqlSession ss = ssf.openSession();
Website site = new Website();
site.setname("編程");
site.setUrl("http");
List<Website> siteList = ss.selectList("net.biancheng.mapper.WebsiteMapper.selectWebsite", site);
for (Website ws : siteList) {
System.out.println(ws);
}
}
}
輸出結(jié)果如下。
DEBUG [main] - ==> Preparing: SELECT id,name,url,age,country FROM website where name LIKE CONCAT ('%',?,'%') AND url like concat ('%',?,'%')
DEBUG [main] - ==> Parameters: 編程(String), http(String)
DEBUG [main] - <== Total: 1
Website[id=1,name=編程幫,url=http://www.jixiangtaizi.com.cn/,age=10,country=CN]