需要更好的閱讀的體驗請移步 👉 小牛肉的個人博客 👈
文章目錄
動態 SQL是MyBatis強大特性之一。極大的簡化我們拼裝 SQL的操作。
動態 SQL 元素和使用 JSTL 或其他類似基於 XML 的文本處 理器相似。
MyBatis 採用功能強大的基於 OGNL
的表達式來簡化操作。
- if 判斷
- choose (when, otherwise) 分支選擇
- trim (where, set) 字符串截取
- foreach 遍歷集合
1. if 判斷 & OGNL 判斷表達式
//攜帶了哪個字段查詢條件就帶上這個字段的值
public List<Employee> getEmpsByConditionIf(Employee employee);
查詢員工,要求:攜帶了哪個字段查詢條件就帶上這個字段的值
<!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
<select id="getEmpsByConditionIf" resultType="com.smallbeef.mybatis.bean.Employee">
select * from tbl_employee where
<!-- test:判斷表達式(OGNL)
從參數中取值進行判斷
-->
<if test="id!=null">
id=#{id}
</if>
<if test="lastName!=null and lastName!=''">
and last_name like #{lastName}
</if>
<if test="email!=null and email.trim()!=''">
and email=#{email}
</if>
<!-- ognl會進行字符串與數字的轉換判斷 "0"==0 -->
<if test="gender==0 or gender==1">
and gender=#{gender}
</if>
</select>
如果查詢字段email爲空
Employee employee = new Employee(1, "Admin", null, 1);
List<Employee> emps = mapper.getEmpsByConditionIf(employee );
則 查詢語句爲
select * from tbl_employee where id = ? and last_name = ? and gender = ?
2. where 查詢條件
上述寫法我們可以看見一個問題,如果 id=null,那麼查詢語句就變成
select * from tbl_employee where and last_name = ? and gender = ?
語法出錯,and被強行拼接
解決方法有兩種:
- 在
selet * from table_name
後面加上where 1 = 1
,並在所有的條件語句都加上and前綴
則如果id = null,那麼查詢語句任然成立
<!-- public List<Employee> getEmpsByConditionIf(Employee employee); -->
<select id="getEmpsByConditionIf" resultType="com.smallbeef.mybatis.bean.Employee">
select * from tbl_employee where 1 = 1
<if test="id!=null">
and id=#{id}
</if>
<if test="lastName!=null and lastName!=''">
and last_name like #{lastName}
</if>
<if test="email!=null and email.trim()!=''">
and email=#{email}
</if>
<!-- ognl會進行字符串與數字的轉換判斷 "0"==0 -->
<if test="gender==0 or gender==1">
and gender=#{gender}
</if>
</select>
select * from tbl_employee where 1 = 1 and last_name = ? and gender = ?
- 將 if 判斷語句全都寫在
where
標籤中
<select id="getEmpsByConditionIf" resultType="com.smallbeef.mybatis.bean.Employee">
select * from tbl_employee
<!-- where -->
<where>
<if test="id!=null">
and id=#{id}
</if>
<if test="lastName!=null and lastName!= ''">
and last_name like #{lastName}
</if>
<if test="email!=null and email.trim()!= ''">
and email=#{email}
</if>
<!-- ognl會進行字符串與數字的轉換判斷 "0"==0 -->
<if test="gender==0 or gender==1">
and gender=#{gender}
</if>
</where>
</select>
where 會自動剔除多出來的 第一個前綴 and 或者 or
可以看見,上述的做法依然存在漏洞,
如果我們的寫法是把and放在後面:
<select id="getEmpsByConditionIf" resultType="com.smallbeef.mybatis.bean.Employee">
select * from tbl_employee
<where>
<if test="id!=null">
id=#{id} and
</if>
<if test="lastName!=null and lastName!= ''">
last_name like #{lastName} and
</if>
<if test="email!=null and email.trim()!= ''">
email=#{email} and
</if>
<!-- ognl會進行字符串與數字的轉換判斷 "0"==0 -->
<if test="gender==0 or gender==1">
gender=#{gender}
</if>
</where>
</select>
如果 gender 爲空,則查詢語句爲
select * from tbl_employee id = ? and last_name = ? and email = ? and
語法出錯,因爲 where 只能剔除多出來的 第一個前綴 and 或者 or
所以,在使用where標籤的時候,建議把and寫在語句的前面
3. trim 自定義字符串截取
對於上述把and寫在後面的寫法,我們可以使用 trim
標籤 自定義字符串的截取規則
trim 標籤中的屬性:
prefix=""
: 前綴:trim標籤體中是整個字符串拼串 後的結果。
prefix給拼串後的整個字符串加一個前綴prefixOverrides=""
: 前綴覆蓋:
去掉整個字符串前面多餘的字符suffix=""
: 後綴
suffix給拼串後的整個字符串加一個後綴suffixOverrides=""
後綴覆蓋:
去掉整個字符串後面多餘的字符
<select id="getEmpsByConditionTrim" resultType="com.smallbeef.mybatis.bean.Employee">
select * from tbl_employee
<trim prefix="where" suffixOverrides="and">
<if test="id!=null">
id=#{id} and
</if>
<if test="lastName!=null && lastName!=""">
last_name like #{lastName} and
</if>
<if test="email!=null and email.trim()!=""">
email=#{email} and
</if>
<!-- ognl會進行字符串與數字的轉換判斷 "0"==0 -->
<if test="gender==0 or gender==1">
gender=#{gender}
</if>
</trim>
</select>
4. choose 分支選擇
choose (when, otherwise):分支選擇;
等同於 帶了 break 的 swtich-case
如果帶了id就用id查,如果帶了lastName就用lastName查 ; 只會進入其中一個查詢語句
<select id="getEmpsByConditionChoose" resultType="com.smallbeef.mybatis.bean.Employee">
select * from tbl_employee
<where>
<!-- 如果帶了id就用id查,如果帶了lastName就用lastName查;只會進入其中一個 -->
<choose>
<when test="id!=null">
id=#{id}
</when>
<when test="lastName!=null">
last_name like #{lastName} // 模糊查詢
</when>
<when test="email!=null">
email = #{email}
</when>
<otherwise>
gender = 0 //如果上述條件都不符合,則執行此條語句
</otherwise>
</choose>
</where>
</select>
如果 id != null
Employee employee = new Employee(1, "Admin", null, null);
List<Employee> emps = mapper.getEmpsByConditionIf(employee );
則查詢語句爲
select * from tbl_employee id = 1
如果 全爲 null
Employee employee = new Employee(null, null, null, null);
List<Employee> emps = mapper.getEmpsByConditionIf(employee );
則查詢語句爲
select * from tbl_employee gender = 0
5. set 更新
我們之前的更新操作語句是這樣的
<update id="updateEmp">
update tbl_employee
set last_name=#{lastName},email=#{email},gender=#{gender}
where id=#{id}
</update>
需要進行全字段更新
比如:已有數據庫信息 id = 1 , lastName = Jack, email = 123, gender = 1;
我們想要更新它的lastName,則:
Employee employee = new Employee(1, "Admin", 123, 1);
List<Employee> emps = mapper.updateEmp(employee );
set 標籤用來執行更新操作,只更新需要更新的字段:
<!--public void updateEmp(Employee employee); -->
<update id="updateEmp">
<!-- Set標籤的使用 -->
update tbl_employee
<set>
<if test="lastName!=null">
last_name=#{lastName},
</if>
<if test="email!=null">
email=#{email},
</if>
<if test="gender!=null">
gender=#{gender}
</if>
</set>
where id=#{id}
</update>
set 標籤會自動剔除多餘的 ,
比如:已有數據庫信息 id = 1 , lastName = Jack, email = 123, gender = 1;
我們想要更新它的lastName,則:
Employee employee = new Employee(1, "Admin", null, null);
List<Employee> emps = mapper.updateEmp(employee );
可以看見 email 和 gender 都爲空,即該字段不被更新,保持不變。
6. foreach 遍歷集合
foreach 標籤中的屬性:
-
collection:指定要遍歷的集合:
list類型的參數會特殊處理封裝在map中,map的key就叫list -
item:將當前遍歷出的元素賦值給指定的變量
-
separator:每個元素之間的分隔符
-
open:遍歷出所有結果拼接一個開始的字符
-
close:遍歷出所有結果拼接一個結束的字符
-
index:索引。遍歷list的時候是index就是索引,item就是當前值
遍歷map的時候index表示的就是map的key,item就是map的值 -
#{變量名}
就能取出變量的值也就是當前遍歷出的元素
批量查詢
//查詢員工id'在給定集合中的
public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);
<!--public List<Employee> getEmpsByConditionForeach(List<Integer> ids); -->
<select id="getEmpsByConditionForeach" resultType="com.smallbeef.mybatis.bean.Employee">
select * from tbl_employee
<foreach collection="ids" item="item_id" separator=","
open="where id in(" close=")">
#{item_id}
</foreach>
</select>
測試:
List<Employee> list = mapper.getEmpsByConditionForeach(Arrays.asList(1,2,3,4));
for (Employee emp : list)
System.out.println(emp);
批量保存
public void addEmps(@Param("emps")List<Employee> emps);
<!--public void addEmps(@Param("emps")List<Employee> emps); -->
<!--MySQL下批量保存:可以foreach遍歷 mysql支持values(),(),()語法-->
<insert id="addEmps">
insert into tbl_employee
values
<foreach collection="emps" item="emp" separator=",">
(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
</foreach>
</insert>
測試:
@Test
public void testBatchSave() throws IOException{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
List<Employee> emps = new ArrayList<>();
emps.add(new Employee(null, "smith0x1", "[email protected]", "1",new Department(1)));
emps.add(new Employee(null, "allen0x1", "[email protected]", "0",new Department(1)));
mapper.addEmps(emps);
openSession.commit();
}finally{
openSession.close();
}
}
7. 兩個內置參數 _databaseId / _parameter
兩個內置參數:
不只是方法傳遞過來的參數可以被用來判斷,取值
mybatis默認還有兩個內置參數:
-
_parameter
: 代表整個參數
單個參數:_parameter就是這個參數
多個參數:參數會被封裝爲一個map;_parameter就是代表這個map -
_databaseId
: 如果配置了databaseIdProvider標籤。
_databaseId就是代表當前數據庫的別名oracle
<!--public List<Employee> getEmpsTestInnerParameter(Employee employee); -->
<select id="getEmpsTestInnerParameter" resultType="com.smakk.mybatis.bean.Employee">
<if test="_databaseId=='mysql'">
select * from tbl_employee
<if test="_parameter!=null">
where last_name like #{lastName}
</if>
</if>
<if test="_databaseId=='oracle'">
select * from employees
<if test="_parameter!=null">
where last_name like #{_parameter.lastName}
</if>
</if>
</select>
8. bind 綁定
bind 元素可以從 OGNL 表達式中創建一個變量並將其綁定到上下文。
比如:
<!--public List<Employee> getEmpsTestInnerParameter(Employee employee); -->
<select id="getEmpsTestInnerParameter" resultType="com.atguigu.mybatis.bean.Employee">
<bind name="_lastName" value="'%'+lastName+'%'"/>
<if test="_databaseId=='mysql'">
select * from tbl_employee
<if test="_parameter!=null">
where last_name like #{lastName}
</if>
</if>
</select>
測試:
Employee employee2 = new Employee();
employee2.setLastName("e");
List<Employee> list = mapper.getEmpsTestInnerParameter(employee2);
for (Employee employee : list)
System.out.println(employee);
lastName 的值 e
被 bind 拼接成 %e%
,即由精確查詢—> 模糊查詢
9. sql 抽取可重用的 sql 片段
抽取可重用的sql片段。方便後面引用
sql
抽取:經常將要查詢的列名,或者插入用的列名抽取出來方便引用include
來引用已經抽取的sql:- include 還可以自定義一些
property
,可在sql標籤內部通過${prop}
取出對應值
不能使用這種方式 #{prop}
示例如下:
<sql id="insertColumn">
<if test="_databaseId=='oracle'">
employee_id,last_name,email,${testColumn}
</if>
<if test="_databaseId=='mysql'">
last_name,email,gender,d_id
</if>
</sql>
<insert id="addEmps" databaseId="oracle">
insert into employees(
<!-- 引用外部定義的sql -->
<include refid="insertColumn">
<property name="testColomn" value="abc"/>
</include>
)
<foreach collection="emps" item="emp" separator="union"
open="select employees_seq.nextval,lastName,email from("
close=")">
select #{emp.lastName} lastName,#{emp.email} email from dual
</foreach>
</insert>