MyBatis動(dòng)態(tài)SQL之<choose><when><o(jì)therwise>標(biāo)簽的使用
簡(jiǎn)介
MyBatis 中動(dòng)態(tài)語(yǔ)句 choose-when-otherwise 類似于 Java 中的 switch-case-default 語(yǔ)句。由于 MyBatis 并沒(méi)有為 if 提供對(duì)應(yīng)的 else 標(biāo)簽,如果想要達(dá)到…… 的效果,可以借助 、、 來(lái)實(shí)現(xiàn)。
語(yǔ)法
<choose> <when test="判斷條件1"> SQL語(yǔ)句1 </when > <when test="判斷條件2"> SQL語(yǔ)句2 </when > <when test="判斷條件3"> SQL語(yǔ)句3 </when > <otherwise> SQL語(yǔ)句4 </otherwise> </choose>
hoose 標(biāo)簽按順序判斷其內(nèi)部 when 標(biāo)簽中的判斷條件是否成立,如果有一個(gè)成立,則執(zhí)行相應(yīng)的 SQL 語(yǔ)句,choose 執(zhí)行結(jié)束;如果都不成立,則執(zhí)行 otherwise 中的 SQL 語(yǔ)句。這類似于 Java 的 switch 語(yǔ)句,choose 為 switch,when 為 case,otherwise 則為 default。
場(chǎng)景示例
MyBatis 就會(huì)根據(jù)參數(shù)的設(shè)置進(jìn)行判斷來(lái)動(dòng)態(tài)組裝 SQL
以下示例要求:
- 當(dāng)網(wǎng)站名稱不為空時(shí),只用網(wǎng)站名稱作為條件進(jìn)行模糊查詢;
- 當(dāng)網(wǎng)站名稱為空,而網(wǎng)址不為空時(shí),則用網(wǎng)址作為條件進(jìn)行模糊查詢;
- 當(dāng)網(wǎng)站名稱和網(wǎng)址都為空時(shí),則要求網(wǎng)站年齡不為空。
<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>
choose-when-otherwise標(biāo)簽-完整案例
1.數(shù)據(jù)庫(kù)準(zhǔn)備
# 創(chuàng)建一個(gè)名稱為t_customer的表 CREATE TABLE t_customer ( id int(32) PRIMARY KEY AUTO_INCREMENT, username varchar(50), jobs varchar(50), phone varchar(16) ); # 插入3條數(shù)據(jù) INSERT INTO t_customer VALUES ('1', 'joy', 'teacher', '13733333333'); INSERT INTO t_customer VALUES ('2', 'jack', 'teacher', '13522222222'); INSERT INTO t_customer VALUES ('3', 'tom', 'worker', '15111111111');
2.新建項(xiàng)目或Module
3 pom.xml中添加
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>mybatis</artifactId> <groupId>com.example</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.biem</groupId> <artifactId>dynamaicSql</artifactId> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <!--1.引入mybatis包--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!--2.單元測(cè)試--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--3.mysql驅(qū)動(dòng)--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.18</version> <scope>runtime</scope> </dependency> <!--4.log4j日志--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> </dependency> </dependencies> </project>
4.創(chuàng)建package和文件夾
src/main/java/下創(chuàng)建package
com.biem.pojo
com.biem.mapper
com.biem.util
src/main/resources/下創(chuàng)建文件夾
com/biem/mapper
src/test/java下創(chuàng)建package
com.biem.test
5 框架配置文件
5.1 mybatis核心配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!--引入properties文件--> <properties resource="jdbc.properties"></properties> <!--將下劃線映射為駝峰--> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!--設(shè)置類型別名--> <typeAliases> <!-- 以包為單位,將包下所有的類型設(shè)置設(shè)置默認(rèn)的類型別名,即類名且不區(qū)分大小寫 --> <package name="com.biem.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!-- 引入映射文件 --> <mappers> <!-- 以包為單位引入映射文件 要求: 1. mapper接口所在的包要和映射文件所在的包一致 2. mapper接口要和映射文件的名字一致 --> <package name="com.biem.mapper"/> </mappers> </configuration>
5.2 mybatis屬性文件jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC jdbc.username=root jdbc.password=root
5.3 log4j.xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <param name="Encoding" value="UTF-8"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/> </layout> </appender> <logger name="java.sql"> <level value="debug"/> </logger> <logger name="org.apache.ibatis"> <level value="info"/> </logger> <root> <level value="debug"/> <appender-ref ref="STDOUT"/> </root> </log4j:configuration>
6 用戶配置文件
6.1 實(shí)體類
package com.biem.pojo; import lombok.*; /** * ClassName: Customer * Package: com.biem.pojo * Description: * * @Create 2023/4/5 22:17 * @Version 1.0 */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder @ToString public class Customer { private Integer id; private String username; private String jobs; private String phone; }
需要在pom.xml中引入lombok,簡(jiǎn)化原來(lái)的實(shí)體類的代碼
6.2 mybatis接口類
package com.biem.mapper; /** * ClassName: CustomerMapper * Package: com.biem.mapper * Description: * * @Create 2023/4/5 22:19 * @Version 1.0 */ public interface CustomerMapper { }
6.3 mybatis用戶配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.biem.mapper.CustomerMapper"> <!-- namespace要和mapper接口的全類名保持一致,例如com.biem.mybatis.mapper.xxxMapper --> <!-- sql語(yǔ)句要和接口的方法名保持一致 --> </mapper>
6.4 mybatis工具類
package com.biem.util; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; /** * ClassName: MybatisUtil * Package: com.biem.utils * Description: * * @Create 2023/4/5 22:23 * @Version 1.0 */ public class MybatisUtil { //利用static(靜態(tài))屬于類不屬于對(duì)象,且全局唯一 private static SqlSessionFactory sqlSessionFactory = null; //利用靜態(tài)塊在初始化類時(shí)實(shí)例化sqlSessionFactory static { InputStream is= null; try { is = Resources.getResourceAsStream("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { e.printStackTrace(); throw new ExceptionInInitializerError(e); } } /** * openSession 創(chuàng)建一個(gè)新的SqlSession對(duì)象 * @return SqlSession對(duì)象 */ public static SqlSession openSession(boolean autoCommit){ return sqlSessionFactory.openSession(autoCommit); } public static SqlSession openSession(){ return sqlSessionFactory.openSession(); } /** * 釋放一個(gè)有效的SqlSession對(duì)象 * @param session 準(zhǔn)備釋放SqlSession對(duì)象 */ public static void closeSession(SqlSession session){ if(session != null){ session.close(); } } }
項(xiàng)目結(jié)構(gòu)如下
7 標(biāo)簽功能測(cè)試
在使用if標(biāo)簽時(shí),只要test屬性中的表達(dá)式為true,就會(huì)執(zhí)行元素中的條件語(yǔ)句,但是在實(shí)際情況下有時(shí)只需要從多個(gè)選項(xiàng)中選擇一個(gè)去執(zhí)行,比如下面的場(chǎng)景:當(dāng)查詢數(shù)據(jù)庫(kù)t_customer時(shí),
- 客戶姓名不為空,則只根據(jù)客戶名稱進(jìn)行客戶篩選,
- 當(dāng)客戶名稱為null的時(shí)候,可客戶職業(yè)不為空,則根據(jù)客戶職業(yè)進(jìn)行篩選,
- 當(dāng)客戶名稱和客戶職業(yè)都為空的時(shí)候,要求查詢電話不為空的客戶
7.1 com.biem.mapper.CustomerMapper.class中添加
public List<Customer> findCustomerByCondition(Customer customer);
7.2 com/biem/mapper/CustomerMapper.xml中添加
<!-- public List<Customer> findCustomerByCondition(Customer customer);--> <select id="findCustomerByCondition" parameterType="customer" resultType="customer"> select * from t_customer where 1=1 <!--條件判斷--> <choose> <when test="username!=null and username!=''"> and username like concat('%',#{username},'%') </when> <when test="jobs!=null and jobs!=''"> and jobs=#{jobs} </when> <otherwise> and phone is not null </otherwise> </choose> </select>
8 功能測(cè)試
在src/test/java中創(chuàng)建類com.biem.test.TestCustomer.java,內(nèi)容如下
package com.biem.test; import com.biem.mapper.CustomerMapper; import com.biem.pojo.Customer; import com.biem.util.MybatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.util.List; /** * ClassName: TestCustomer * Package: com.biem.test * Description: * * @Create 2023/4/5 22:32 * @Version 1.0 */ public class TestCustomer { @Test public void testFindAll(){ // 通過(guò)工具類獲取SqlSession對(duì)象 SqlSession session = MybatisUtil.openSession(); // 創(chuàng)建Customer對(duì)象,封裝需要組合查詢的條件 Customer customer = new Customer(); CustomerMapper mapper = session.getMapper(CustomerMapper.class); List<Customer> customers = mapper.findCustomerByCondition(customer); System.out.println("customers = " + customers); // 關(guān)閉SqlSession session.close(); } @Test public void testFindCustomerByName(){ // 通過(guò)工具類獲取SqlSession對(duì)象 SqlSession session = MybatisUtil.openSession(); // 創(chuàng)建Customer對(duì)象,封裝需要組合查詢的條件 Customer customer = new Customer(); customer.setUsername("jack"); CustomerMapper mapper = session.getMapper(CustomerMapper.class); List<Customer> customers = mapper.findCustomerByCondition(customer); System.out.println("customers = " + customers); // 關(guān)閉SqlSession session.close(); } @Test public void testFindCustomerByJobs(){ // 通過(guò)工具類獲取SqlSession對(duì)象 SqlSession session = MybatisUtil.openSession(); // 創(chuàng)建Customer對(duì)象,封裝需要組合查詢的條件 Customer customer = new Customer(); customer.setJobs("teacher"); CustomerMapper mapper = session.getMapper(CustomerMapper.class); List<Customer> customers = mapper.findCustomerByCondition(customer); System.out.println("customers = " + customers); // 關(guān)閉SqlSession session.close(); } @Test public void testFindCustomerByPhone(){ // 通過(guò)工具類獲取SqlSession對(duì)象 SqlSession session = MybatisUtil.openSession(); // 創(chuàng)建Customer對(duì)象,封裝需要組合查詢的條件 Customer customer = new Customer(); customer.setPhone("1"); CustomerMapper mapper = session.getMapper(CustomerMapper.class); List<Customer> customers = mapper.findCustomerByCondition(customer); System.out.println("customers = " + customers); // 關(guān)閉SqlSession session.close(); } }
到此這篇關(guān)于MyBatis動(dòng)態(tài)SQL之<choose><when><o(jì)therwise>標(biāo)簽的使用的文章就介紹到這了,更多相關(guān)MyBatis <choose><when><o(jì)therwise>標(biāo)簽內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)超詳細(xì)分析二叉搜索樹(shù)
二叉搜索樹(shù)是以一棵二叉樹(shù)來(lái)組織的。每個(gè)節(jié)點(diǎn)是一個(gè)對(duì)象,包含的屬性有l(wèi)eft,right,p和key,其中,left指向該節(jié)點(diǎn)的左孩子,right指向該節(jié)點(diǎn)的右孩子,p指向該節(jié)點(diǎn)的父節(jié)點(diǎn),key是它的值2022-03-03java gui實(shí)現(xiàn)計(jì)算器小程序
這篇文章主要為大家詳細(xì)介紹了java gui實(shí)現(xiàn)計(jì)算器小程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07java案例實(shí)戰(zhàn)之字符串轉(zhuǎn)換為二進(jìn)制
最近遇到個(gè)需求,要求編寫一個(gè)程序,從鍵盤錄入一個(gè)字符串,將字符串轉(zhuǎn)換為二進(jìn)制數(shù),下面這篇文章主要給大家介紹了關(guān)于java字符串轉(zhuǎn)換為二進(jìn)制的相關(guān)資料,需要的朋友可以參考下2023-06-06Mybatis返回單個(gè)實(shí)體或者返回List的實(shí)現(xiàn)
這篇文章主要介紹了Mybatis返回單個(gè)實(shí)體或者返回List的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07PropertiesLoaderUtils 出現(xiàn)中文亂碼的解決方式
這篇文章主要介紹了PropertiesLoaderUtils 出現(xiàn)中文亂碼的解決方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08Spring?Security?基于URL的權(quán)限判斷源碼解析
這篇文章主要介紹了Spring?Security?基于URL的權(quán)限判斷問(wèn)題,我們想要實(shí)現(xiàn)自己的基于請(qǐng)求Url的授權(quán)只需自定義一個(gè)?AccessDecisionManager即可,接下來(lái)跟隨小編一起看看實(shí)現(xiàn)代碼吧2021-12-12