今天,主要學習MyBatis的動態SQL。這是MyBatis的強大特性之一。
動態SQL的作用
MyBatis的動態SQL主要就是為了解決手動拼接SQL的麻煩
動態SQL中的元素
動態SQL是MyBatis的強大特性之一,MyBatis3采用了功能強大的基於OGNL的表達式來完成動態SQL。動態SQL主要元素如下表所示:
1.<if> 元素
在MyBatis中,<if>元素是最常用的判斷語句,它類似於Java中的if語句,主要用於實現某些簡單的條件選擇。其基本使用示例如下:
<select id="findCustomerByNameAndJobs" parameterType="com.ma.po.Customer" resultType="com.ma.po.Customer">
select * from t_customer where 1=1
<if test="username != null and username != ''">
and username like '%${username}%'
</if>
<if test="jobs != null and jobs !=''">
and jobs = #{jobs}
</if>
</select>
2.<choose>、<when>、<otherwise>元素
如果是java語言,這種情況就相當於switch...case...default語句。
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>
3. <where>、<trim>元素
在前面案例中,映射文件中編寫的SQL后面都加入了“where 1=1”的條件,那么到底為什么要這么寫呢?如果將where后“1=1”的條件去掉,那么MyBatis所拼接出來的SQL將會如下所示
select * from t_customer where and username like '%'? '%'
可以看出上面SQL語句明顯存在SQL語法錯誤,而加入了條件“1=1”后,既保證了where后面的條件成立,又避免了where后面第一個詞是and或者or之類的關鍵詞。
不過“where 1=1”這種寫法對於初學者來將不容易理解,並且也不夠雅觀。
針對上述情況中“where 1=1”,在MyBatis的SQL中就可以使用
select * from t_customer
<where>
<if test="username !=null and username !=''">
and username like concat('%',#{username}, '%')
</if>
<if test="jobs !=null and jobs !=''">
and jobs= #{jobs}
</if>
</where>
上述代碼中,使用<where>元素對“where 1=1”條件進行了替換,<where>元素會自動判斷組合條件下拼裝的SQL語句,只有<where>內的條件成立時,才會在拼接SQL中加入where關鍵字,否則將不會添加;
即使where之后的內容有多余的“AND”或“OR”,<where>元素也會自動將它們去除。
select * from t_customer
<trim prefix="where" prefixOverrides="and">
<if test="username !=null and username !=''">
and username like concat('%',#{username}, '%')
</if>
<if test="jobs !=null and jobs !=''">
and jobs= #{jobs}
</if>
</trim>
<trim>的作用是去除特殊的字符串,它的prefix屬性代表語句的前綴,prefixOverrides屬性代表需要去除的哪些特殊字符串,功能和<where>基本是等效的。
4.<set>元素
在Hibernate中,想要更新某個對象,就需要發送所有的字段給持久化對象,這種想更新的每一條數據都要將其所有的屬性都更新一遍的方法,其執行效率是非常差的。為此,在MyBatis中可以使用動態SQL中的<set>元素進行處理:
<update id="updateCustomer" parameterType="com.itheima.po.Customer">
update t_customer
<set>
<if test="username !=null and username !=''">
username=#{username},
</if>
<if test="jobs !=null and jobs !=''">
jobs=#{jobs},
</if>
</set>
where id=#{id}
</update>
上述配置中,使用了<set>和<if>元素結合來組裝update語句。其中<set>元素會動態前置SET關鍵字,同時也會消除SQL語句中最后一個多余的逗號;
<if>元素用於判斷相應的字段是否為空,如果不為空,就將此字段進行動態SQL組裝,並更新此字段,否則不執行更新。
5.<foreach>元素
<foreach>元素是一個循環語句,它的作用是遍歷集合,它能夠很好地支持數組和List、Set接口的集合,對此提供遍歷功能。它往往用於SQL中的in關鍵字。其基本使用示例如下所示:
<select id="findCustomerByIds" parameterType="List"
resultType="com.itheima.po.Customer">
select * from t_customer where id in
-- 判斷為空可以用 list.size>0
<foreach item="id" index="index" collection="list"
open="(" separator="," close=")">
#{id}
</foreach>
</select>
關於上述示例中
-
item:配置的是循環中當前的元素。
-
index:配置的是當前元素在集合的位置下標。
-
collection:配置的list是傳遞過來的參數類型(首字母小寫),它可以是一個array、list(或collection)、Map集合的鍵、POJO包裝類中數組或集合類型的屬性名等。
-
open和close:配置的是以什么符號將這些集合元素包裝起來。
-
separator:配置的是各個元素的間隔符。
注意:
在使用<foreach>時最關鍵也是最容易出錯的就是collection屬性,該屬性是必須指定的,而且在不同情況下,該屬性的值是不一樣的。主要有以下3種情況:
1.如果傳入的是單參數且參數類型是一個數組或者List的時候,collection屬性值分別為array和list(或collection)。
2.如果傳入的參數是多個的時候,就需要把它們封裝成一個Map了,當然單參數也可以封裝成Map集合,這時候collection屬性值就為Map的鍵。
3.如果傳入的參數是POJO包裝類的時候,collection屬性值就為該包裝類中需要進行遍歷的數組或集合的屬性名。
6.<bind>元素
首先,看一下這條sql:
select * from t_customer where username like '%${value}%'
1.如果使用“${}”進行字符串拼接,則無法防止SQL注入問題;
2.如果改用concat函數進行拼接,則只針對MySQL數據庫有效;
3.如果改用“||”進行字符串拼接,則只針對Oracle數據庫有效。
這樣,映射文件中的SQL就要根據不同的情況提供不同形式的實現,這顯然是比較麻煩的,且不利於項目的移植。為了減少這種麻煩,就可以使用MyBatis的
MyBatis的
<select id="findCustomerByName" parameterType="com.itheima.po.Customer"
resultType="com.itheima.po.Customer">
<!--_parameter.getUsername()表示傳遞進來的參數(也可以直接寫成對應的參數變量名,如username)-->
<bind name="pattern_username" value="'%'+_parameter.getUsername()+'%'" />
select * from t_customer
where
<!--需要的地方直接引用<bind>元素的name屬性值即可-->
username like #{pattern_username}
</select>
案例
開發工具:idea
Java環境: jdk1.8.0_121
數據庫:SQLServer
項目結構:
jar包:
實體類Customer
public class Customer {
private Integer id; //主鍵
private String username; //客戶名稱
private String jobs; //職業
private String phone; //電話
//省略setter和getter方法
}
CustomerMapper.xml文件
<?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">
<!--namespace表示命名空間-->
<mapper namespace="com.ma.mapper.CustomerMapper">
<!--if元素使用-->
<select id="findCustomerByNameAndJobs" parameterType="com.ma.po.Customer" resultType="com.ma.po.Customer">
select * from t_customer where 1=1
<if test="username != null and username != ''">
and username like '%${username}%'
</if>
<if test="jobs != null and jobs !=''">
and jobs = #{jobs}
</if>
</select>
<!--choose when otherwise使用-->
<select id="findCustomerByNameOrJobs" parameterType="com.ma.po.Customer" resultType="com.ma.po.Customer">
select * from t_customer where 1=1
<choose>
<when test="username != null and username !=''">
and username like '%${username}%'
</when>
<when test="jobs != null and jobs != ''">
and jobs = #{jobs}
</when>
<otherwise>
and phone is not null
</otherwise>
</choose>
</select>
<!--where trim 使用-->
<select id="findCustomerByNameAndJobs1" parameterType="com.ma.po.Customer" resultType="com.ma.po.Customer">
select * from t_customer
<where>
<if test="username != null and username != ''">
and username like '%${username}%'
</if>
<if test="jobs != null and jobs !=''">
and jobs = #{jobs}
</if>
</where>
</select>
<!--where trim 使用-->
<select id="findCustomerByNameAndJobs2" parameterType="com.ma.po.Customer" resultType="com.ma.po.Customer">
select * from t_customer
<trim prefix="where" prefixOverrides="and">
<if test="username != null and username != ''">
and username like '%${username}%'
</if>
<if test="jobs != null and jobs !=''">
and jobs = #{jobs}
</if>
</trim>
<if test="username != null and username != ''">
and username like '%${username}%'
</if>
<if test="jobs != null and jobs !=''">
and jobs = #{jobs}
</if>
</select>
<!--set使用-->
<update id="updateCustomer" parameterType="com.ma.po.Customer">
update t_customer
<set>
<if test="username != null and username != ''">
username = #{username}
</if>
<if test="jobs != null and jobs != ''">
jobs = #{jobs}
</if>
<if test="phone != null and phone != ''">
phone = #{phone},
</if>
</set>
where id = #{id}
</update>
<!--foreach元素使用-->
<select id="findCustomerByIds" parameterType="List" resultType="com.ma.po.Customer">
select * from t_customer where id in
<foreach item="id" collection="list" open="(" separator="," close=")">
#{id}
</foreach>
</select>
<!--bind元素使用,根據客戶名模糊查詢信息-->
<select id="findCustomerByName" parameterType="com.ma.po.Customer" resultType="com.ma.po.Customer">
<!--_parameter.getUsername()也可以直接寫成傳入的字段屬性名,即username-->
<bind name="pattern_username" value="'%'+_parameter.getUsername()+'%'"/>
select * from t_customer
where
username like #{pattern_username}
</select>
</mapper>
MybatisTest
package com.ma.test;
import com.ma.po.Customer;
import com.ma.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* @author mz
* @version V1.0
* @Description: Mybatis測試
* @create 2017-11-01 15:20
*/
public class MybatisTest {
/**
* 根據姓名和職業查詢客戶if
*/
@Test
public void findCustomerByNameAndJobsTest() {
//獲取SqlSession
SqlSession sqlSession = MybatisUtils.getSession();
//創建Customer對象,封裝需要組合查詢的條件
Customer customer = new Customer();
customer.setUsername("jack");
customer.setJobs("teacher");
//執行SqlSession的查詢方法,返回結果集
List<Customer>customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByNameAndJobs", customer);
//輸出結果
for (Customer customer1 : customers) {
System.out.println(customer1);
}
//關閉SqlSession
sqlSession.close();
}
/**
* 根據客戶名或職業查詢客戶信息choose when otherwise
*/
@Test
public void findCustomerByNameOrJobsTest() {
//獲取SqlSession
SqlSession sqlSession = MybatisUtils.getSession();
//創建Customer對象,封裝需要組合查詢的條件
Customer customer = new Customer();
customer.setUsername("jack");
customer.setJobs("teacher");
//執行SqlSession的查詢方法,返回結果集
List<Customer> list = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByNameOrJobs", customer);
for (Customer customer1 : list) {
System.out.println(customer1);
}
//關閉SqlSession
sqlSession.close();
}
/**
* 根據姓名和職業查詢客戶where
*/
@Test
public void findCustomerByNameAndJobs1Test() {
//獲取SqlSession
SqlSession sqlSession = MybatisUtils.getSession();
//創建Customer對象,封裝需要組合查詢的條件
Customer customer = new Customer();
customer.setUsername("jack");
customer.setJobs("teacher");
//執行SqlSession的查詢方法,返回結果集
List<Customer>customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByNameAndJobs1", customer);
//輸出結果
for (Customer customer1 : customers) {
System.out.println(customer1);
}
//關閉SqlSession
sqlSession.close();
}
/**
* 根據姓名和職業查詢客戶trim
*/
@Test
public void findCustomerByNameAndJobs2Test() {
//獲取SqlSession
SqlSession sqlSession = MybatisUtils.getSession();
//創建Customer對象,封裝需要組合查詢的條件
Customer customer = new Customer();
customer.setUsername("jack");
customer.setJobs("teacher");
//執行SqlSession的查詢方法,返回結果集
List<Customer>customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByNameAndJobs2", customer);
//輸出結果
for (Customer customer1 : customers) {
System.out.println(customer1);
}
//關閉SqlSession
sqlSession.close();
}
/**
* 更新數據,set測試
*/
@Test
public void updateCustomerTest() {
//獲取SqlSession
SqlSession sqlSession = MybatisUtils.getSession();
//創建Customer對象,封裝需要組合查詢的條件
Customer customer = new Customer();
customer.setId(3);
customer.setPhone("1254587855");
//執行SqlSession的查詢方法,返回影響行數
int rows = sqlSession.update("com.ma.mapper.CustomerMapper.updateCustomer", customer);
if (rows > 0) {
System.out.println("修改了"+ rows +"條數據!");
} else {
System.out.println("failed");
}
//提交事務
sqlSession.commit();
//關閉SqlSession
sqlSession.close();
}
/**
* foreach測試
*/
@Test
public void findCustomerByIdsTest() {
//獲取SqlSession
SqlSession sqlSession = MybatisUtils.getSession();
//創建List集合,封裝查詢id
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
//執行SqlSession的查詢方法,返回結果集
List<Customer> customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByIds", ids);
for (Customer customer : customers) {
System.out.println(customer);
}
//關閉SqlSession
sqlSession.close();
}
/**
* 模糊查詢bind
*/
@Test
public void findCustomerByNameTest() {
//獲取SqlSession
SqlSession sqlSession = MybatisUtils.getSession();
//創建Customer對象,封裝需要組合查詢的條件
Customer customer = new Customer();
customer.setUsername("j");
//執行SqlSession的查詢方法,返回結果集
List<Customer> customers = sqlSession.selectList("com.ma.mapper.CustomerMapper.findCustomerByName", customer);
for (Customer customer1 : customers) {
System.out.println(customer1);
}
//關閉SqlSession
sqlSession.close();
}
}
部分運行結果
小結
首先對MyBatis框架的動態SQL元素作了簡要了解,然后分別對這些主要的動態SQL元素進行了詳細說明。
通過學習可以了解常用動態SQL元素的主要作用,並能夠掌握這些元素在實際開發中如何使用。
在MyBatis框架中,這些動態SQL元素的使用十分重要,熟練的掌握它們能夠極大的提高開發效率。
以上內容是根據Java EE企業級應用開發教程(Spring+Spring MVC+MyBatis)做的一些筆記和總結。