用mybatis對一張表進行的CRUD操作,但是我們發現寫的 SQL 語句都比較簡單,如果有比較複雜的業務,我們需要寫複雜的 SQL 語句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都會導緻錯誤。
那麼怎麼去解決這個問題呢?這就是本篇所講的使用 mybatis 動态SQL,通過 if, choose, when, otherwise, trim, where, set, foreach等标簽,可組合成非常靈活的SQL語句,進而在提高 SQL 語句的準确性的同時,也大大提高了開發人員的效率。
我們以 User 表為例來說明:

1、動态SQL:if 語句
根據 username 和 sex 來查詢資料。如果username為空,那麼将隻根據sex來查詢;反之隻根據username來查詢
首先不使用 動态SQL 來書寫
<select id="selectUserByUsernameAndSex"
resultType="user" parameterType="com.ys.po.User">
<!-- 這裡和普通的sql 查詢語句差不多,對于隻有一個參數,後面的 #{id}表示占位符,裡面不一定要寫id,
寫啥都可以,但是不要空着,如果有多個參數則必須寫pojo類裡面的屬性 -->
select * from user where username=#{username} and sex=#{sex}
</select>
鄭州不育不孕醫院:http://www.zzchyy110.com/
上面的查詢語句,我們可以發現,如果 #{username} 為空,那麼查詢結果也是空,如何解決這個問題呢?使用 if 來判斷
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
select * from user where
<if test="username != null">
username=#{username}
</if>
http://www.chacha8.cn/detail/1132398241.html
<if test="sex != null">
and sex=#{sex}
這樣寫我們可以看到,如果 sex 等于 null,那麼查詢語句為 select * from user where username=#{username},但是如果usename 為空呢?那麼查詢語句為 select * from user where and sex=#{sex},這是錯誤的 SQL 語句,如何解決呢?請看下面的 where 語句
2、動态SQL:if+where 語句
select * from user
<where>
</where>
這個“where”标簽會知道如果它包含的标簽中有傳回值的話,它就插入一個‘where’。此外,如果标簽傳回的内容是以AND 或OR 開頭的,則它會剔除掉。
3、動态SQL:if+set 語句
同理,上面的對于查詢 SQL 語句包含 where 關鍵字,如果在進行更新操作的時候,含有 set 關鍵詞,我們怎麼處理呢?
<!-- 根據 id 更新 user 表的資料 -->
<update id="updateUserById" parameterType="com.ys.po.User">
update user u
<set>
<if test="username != null and username != ''">
u.username = #{username},
</if>
<if test="sex != null and sex != ''">
u.sex = #{sex},
</set>
where id=#{id}
</update>
這樣寫,如果第一個條件 username 為空,那麼 sql 語句為:update user u set u.sex=? where id=?
如果第一個條件不為空,那麼 sql 語句為:update user u set u.username = ? ,u.sex = ? where id=?
最後的,也會别自動删掉。
4、動态SQL:choose(when,otherwise) 語句
有時候,我們不想用到所有的查詢條件,隻想選擇其中的一個,查詢條件有一個滿足即可,使用 choose 标簽可以解決此類問題,類似于 Java 的 switch 語句
<select id="selectUserByChoose" resultType="com.ys.po.User" parameterType="com.ys.po.User">
select * from user
<where>
<choose>
<when test="id !='' and id != null">
id=#{id}
</when>
<when test="username !='' and username != null">
and username=#{username}
<otherwise>
and sex=#{sex}
</otherwise>
</choose>
</where>
</select>
也就是說,這裡我們有三個條件,id,username,sex,隻能選擇一個作為查詢條件
如果 id 不為空,那麼查詢語句為:select * from user where id=?
如果 id 為空,那麼看username 是否為空,如果不為空,那麼語句為 select * from user where username=?;
如果 username 為空,那麼查詢語句為 select * from user where sex=?
5、動态SQL:trim 語句
trim标記是一個格式化的标記,可以完成set或者是where标記的功能
①、用 trim 改寫上面第二點的 if+where 語句
select * from user
<!-- <where>
<if test="username != null">
username=#{username}
and sex=#{sex}
</where> -->
<trim prefix="where" prefixOverrides="and | or">
and username=#{username}
<if test="sex != null">
</trim>
</select>
prefix:字首
prefixoverride:去掉第一個and或者是or
②、用 trim 改寫上面第三點的 if+set 語句
<update id="updateUserById" parameterType="com.ys.po.User">
update user u
<!-- <set>
<if test="username != null and username != ''">
u.username = #{username},
</if>
<if test="sex != null and sex != ''">
u.sex = #{sex}
</set> -->
<trim prefix="set" suffixOverrides=",">
u.sex = #{sex},
</trim>
where id=#{id}
</update>
suffix:字尾
suffixoverride:去掉最後一個逗号(也可以是其他的标記,就像是上面字首中的and一樣)
6、動态SQL: SQL 片段
有時候可能某個 sql 語句我們用的特别多,為了增加代碼的重用性,簡化代碼,我們需要将這些代碼抽取出來,然後使用時直接調用。
比如:假如我們需要經常根據使用者名和性别來進行聯合查詢,那麼我們就把這個代碼抽取出來,如下:
<!-- 定義 sql 片段 -->
<sql id="selectUserByUserNameAndSexSQL">
<if test="username != null and username != ''">
AND username = #{username}
</if>
<if test="sex != null and sex != ''">
AND sex = #{sex}
</sql>
引用 sql 片段
<trim prefix="where" prefixOverrides="and | or">
<!-- 引用 sql 片段,如果refid 指定的不在本檔案中,那麼需要在前面加上 namespace -->
<include refid="selectUserByUserNameAndSexSQL"></include>
<!-- 在這裡還可以引用其他的 sql 片段 -->
</trim>
注意:①、最好基于 單表來定義 sql 片段,提高片段的可重用性
②、在 sql 片段中最好不要包括 where
7、動态SQL: foreach 語句
需求:我們需要查詢 user 表中 id 分别為1,2,3的使用者
sql語句:select * from user where id=1 or id=2 or id=3
select * from user where id in (1,2,3)
①、建立一個 UserVo 類,裡面封裝一個 List<Integer> ids 的屬性
package com.ys.vo;
import java.util.List;
public class UserVo {
//封裝多個使用者的id
private List<Integer> ids;
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
②、我們用 foreach 來改寫 select * from user where id=1 or id=2 or id=3
<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
<!--
collection:指定輸入對象中的集合屬性
item:每次周遊生成的對象
open:開始周遊時的拼接字元串
close:結束時拼接的字元串
separator:周遊對象之間需要拼接的字元串
select * from user where 1=1 and (id=1 or id=2 or id=3)
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
測試:
//根據id集合查詢user表資料
@Test
public void testSelectUserByListId(){
String statement = "com.ys.po.userMapper.selectUserByListId";
UserVo uv = new UserVo();
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
uv.setIds(ids);
List<User> listUser = session.selectList(statement, uv);
for(User u : listUser){
System.out.println(u);
session.close();
}
③、我們用 foreach 來改寫 select * from user where id in (1,2,3)
<where>
<!--
collection:指定輸入對象中的集合屬性
item:每次周遊生成的對象
open:開始周遊時的拼接字元串
close:結束時拼接的字元串
separator:周遊對象之間需要拼接的字元串
select * from user where id in (1,2,3)
-->
<foreach collection="ids" item="id" open="and id in (" close=") " separator=",">
#{id}
</foreach>
</where>
8、總結
其實動态 sql 語句的編寫往往就是一個拼接的問題,為了保證拼接準确,我們最好首先要寫原生的 sql 語句出來,然後在通過 mybatis 動态sql 對照着改,防止出錯。