MyBatis06:動态SQL
介紹
什麼是動态SQL:動态SQL指的是根據不同的查詢條件 , 生成不同的Sql語句.
官網描述:
MyBatis 的強大特性之一便是它的動态 SQL。如果你有使用 JDBC 或其它類似架構的經驗,你就能體會到根據不同條件拼接 SQL 語句的痛苦。例如拼接時要確定不能忘記添加必要的空格,還要注意去掉清單最後一個列名的逗号。利用動态 SQL 這一特性可以徹底擺脫這種痛苦。
雖然在以前使用動态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射語句中的強大的動态 SQL 語言得以改進這種情形。
動态 SQL 元素和 JSTL 或基于類似 XML 的文本處理器相似。在 MyBatis 之前的版本中,有很多元素需要花時間了解。MyBatis 3 大大精簡了元素種類,現在隻需學習原來一半的元素便可。MyBatis 采用功能強大的基于 OGNL 的表達式來淘汰其它大部分元素。
-------------------------------
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
-------------------------------
我們之前寫的 SQL 語句都比較簡單,如果有比較複雜的業務,我們需要寫複雜的 SQL 語句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都會導緻錯誤。
那麼怎麼去解決這個問題呢?這就要使用 mybatis 動态SQL,通過 if, choose, when, otherwise, trim, where, set, foreach等标簽,可組合成非常靈活的SQL語句,進而在提高 SQL 語句的準确性的同時,也大大提高了開發人員的效率。
搭建環境
建立一個資料庫表:blog
字段:id,title,author,create_time,views
CREATE TABLE `blog` (
`id` varchar(50) NOT NULL COMMENT '部落格id',
`title` varchar(100) NOT NULL COMMENT '部落格标題',
`author` varchar(30) NOT NULL COMMENT '部落格作者',
`create_time` datetime NOT NULL COMMENT '建立時間',
`views` int(30) NOT NULL COMMENT '浏覽量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1、建立Mybatis基礎工程

2、IDutil工具類
public class IDUtil {
public static String genId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
3、實體類編寫 【注意set方法作用】
import java.util.Date;
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
//set,get....
}
4、編寫Mapper接口及xml檔案
public interface BlogMapper {
}
<?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.kuang.mapper.BlogMapper">
</mapper>
5、mybatis核心配置檔案,下劃線駝峰自動轉換
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--注冊Mapper.xml-->
<mappers>
<mapper resource="mapper/BlogMapper.xml"/>
</mappers>
6、插入初始資料
編寫接口
//新增一個部落格
int addBlog(Blog blog);
sql配置檔案
<insert id="addBlog" parameterType="blog">
insert into blog (id, title, author, create_time, views)
values (#{id},#{title},#{author},#{createTime},#{views});
</insert>
初始化部落格方法
@Test
public void addInitBlog(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtil.genId());
blog.setTitle("Mybatis如此簡單");
blog.setAuthor("狂神說");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDUtil.genId());
blog.setTitle("Java如此簡單");
mapper.addBlog(blog);
blog.setId(IDUtil.genId());
blog.setTitle("Spring如此簡單");
mapper.addBlog(blog);
blog.setId(IDUtil.genId());
blog.setTitle("微服務如此簡單");
mapper.addBlog(blog);
session.close();
}
初始化資料完畢!
if 語句
需求:根據作者名字和部落格名字來查詢部落格!如果作者名字為空,那麼隻根據部落格名字查詢,反之,則根據作者名來查詢
1、編寫接口類
//需求1
List<Blog> queryBlogIf(Map map);
2、編寫SQL語句
<!--需求1:
根據作者名字和部落格名字來查詢部落格!
如果作者名字為空,那麼隻根據部落格名字查詢,反之,則根據作者名來查詢
select * from blog where title = #{title} and author = #{author}
-->
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog where
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
3、測試
@Test
public void testQueryBlogIf(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<String, String>();
map.put("title","Mybatis如此簡單");
map.put("author","狂神說");
List<Blog> blogs = mapper.queryBlogIf(map);
System.out.println(blogs);
session.close();
}
這樣寫我們可以看到,如果 author 等于 null,那麼查詢語句為 select * from user where title=#{title},但是如果title為空呢?那麼查詢語句為 select * from user where and author=#{author},這是錯誤的 SQL 語句,如何解決呢?請看下面的 where 語句!
Where
修改上面的SQL語句;
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
這個“where”标簽會知道如果它包含的标簽中有傳回值的話,它就插入一個‘where’。此外,如果标簽傳回的内容是以AND 或OR 開頭的,則它會剔除掉。
Set
同理,上面的對于查詢 SQL 語句包含 where 關鍵字,如果在進行更新操作的時候,含有 set 關鍵詞,我們怎麼處理呢?
1、編寫接口方法
int updateBlog(Map map);
2、sql配置檔案
<!--注意set是用的逗号隔開-->
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id};
</update>
@Test
public void testUpdateBlog(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<String, String>();
map.put("title","動态SQL");
map.put("author","秦疆");
map.put("id","9d6a763f5e1347cebda43e2a32687a77");
mapper.updateBlog(map);
session.close();
}
choose語句
有時候,我們不想用到所有的查詢條件,隻想選擇其中的一個,查詢條件有一個滿足即可,使用 choose 标簽可以解決此類問題,類似于 Java 的 switch 語句
List<Blog> queryBlogChoose(Map map);
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
3、測試類
@Test
public void testQueryBlogChoose(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title","Java如此簡單");
map.put("author","狂神說");
map.put("views",9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
System.out.println(blogs);
session.close();
}
SQL片段
有時候可能某個 sql 語句我們用的特别多,為了增加代碼的重用性,簡化代碼,我們需要将這些代碼抽取出來,然後使用時直接調用。
提取SQL片段:
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
引用SQL片段:
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本檔案中,那麼需要在前面加上 namespace -->
<include refid="if-title-author"></include>
<!-- 在這裡還可以引用其他的 sql 片段 -->
</where>
</select>
注意:
①、最好基于 單表來定義 sql 片段,提高片段的可重用性
②、在 sql 片段中不要包括 where
Foreach
将資料庫中前三個資料的id修改為1,2,3;
需求:我們需要查詢 blog 表中 id 分别為1,2,3的部落格資訊
1、編寫接口
List<Blog> queryBlogForeach(Map map);
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<!--
collection:指定輸入對象中的集合屬性
item:每次周遊生成的對象
open:開始周遊時的拼接字元串
close:結束時拼接的字元串
separator:周遊對象之間需要拼接的字元串
select * from blog 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>
</where>
</select>
@Test
public void testQueryBlogForeach(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap map = new HashMap();
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
System.out.println(blogs);
session.close();
}
小結:其實動态 sql 語句的編寫往往就是一個拼接的問題,為了保證拼接準确,我們最好首先要寫原生的 sql 語句出來,然後在通過 mybatis 動态sql 對照着改,防止出錯。多在實踐中使用才是熟練掌握它的技巧。
動态SQL在開發中大量的使用,一定要熟練掌握!