MyBatis 中動態(tài)語句 choose-when-otherwise 類似于 Java 中的 switch-case-default 語句。由于 MyBatis 并沒有為 if 提供對應(yīng)的 else 標(biāo)簽,如果想要達(dá)到<if>...<else>...</else> </if> 的效果,可以借助 <choose>、<when>、<otherwise> 來實現(xiàn)。
動態(tài)語句 choose-when-otherwise 語法如下。
<choose> <when test="判斷條件1"> SQL語句1 </when> <when test="判斷條件2"> SQL語句2 </when> <when test="判斷條件3"> SQL語句3 </when> <otherwise> SQL語句4 </otherwise> </choose>
choose 標(biāo)簽按順序判斷其內(nèi)部 when 標(biāo)簽中的判斷條件是否成立,如果有一個成立,則執(zhí)行相應(yīng)的 SQL 語句,choose 執(zhí)行結(jié)束;如果都不成立,則執(zhí)行 otherwise 中的 SQL 語句。這類似于 Java 的 switch 語句,choose 為 switch,when 為 case,otherwise 則為 default。
以下示例要求:
當(dāng)網(wǎng)站名稱不為空時,只用網(wǎng)站名稱作為條件進行模糊查詢;
當(dāng)網(wǎng)站名稱為空,而網(wǎng)址不為空時,則用網(wǎng)址作為條件進行模糊查詢;
當(dāng)網(wǎng)站名稱和網(wǎng)址都為空時,則要求網(wǎng)站年齡不為空。
下面使用 choose-when-otherwise 標(biāo)簽實現(xiàn)(本節(jié)示例基于《第一個MyBatis程序》一節(jié)的代碼實現(xiàn))。
WebsiteMapper.xml 代碼如下。
<mapper namespace="net.biancheng.mapper.WebsiteMapper"> <select id="selectWebsite" parameterType="net.biancheng.po.Website" resultType="net.biancheng.po.Website"> SELECT id,name,url,age,country FROM website WHERE 1=1 <choose> <when test="name != null and name !=''"> AND name LIKE CONCAT('%',#{name},'%') </when> <when test="url != null and url !=''"> AND url LIKE CONCAT('%',#{url},'%') </when> <otherwise> AND age is not null </otherwise> </choose> </select> </mapper>
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("編程"); 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 1=1 AND name LIKE CONCAT('%',?,'%') DEBUG [main] - ==> Parameters: 編程(String) DEBUG [main] - <== Total: 1 Website[id=1,name=編程幫,url=https://www.biancheng.net/,age=10,country=CN,createtime=null]
這樣 MyBatis 就會根據(jù)參數(shù)的設(shè)置進行判斷來動態(tài)組裝 SQL,以滿足不同業(yè)務(wù)的要求。遠(yuǎn)比 Hibernate 和 JDBC 中大量判斷 Java 代碼要清晰和明確。