10 動態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 陳述句的準確性的同時,也大大提高了開發人員的效率,
搭建環境
在mybatis資料庫中新建一個表:blog
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基礎工程,module:mybatis-07

2、IDUtil 工具類
package com.zzb.utils;
import java.util.UUID;
public class IDUtil {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
3、撰寫物體類Blog
package com.zzb.pojo;
import java.util.Date;
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
public Blog() {
}
public Blog(String id, String title, String author, Date createTime, int views) {
this.id = id;
this.title = title;
this.author = author;
this.createTime = createTime;
this.views = views;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public int getViews() {
return views;
}
public void setViews(int views) {
this.views = views;
}
@Override
public String toString() {
return "Blog{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", author='" + author + '\'' +
", createTime=" + createTime +
", views=" + views +
'}';
}
}
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.zzb.mapper.BlogMapper">
</mapper>
5、撰寫mybatis核心組態檔,注冊mapper、下劃線駝峰自動轉換以及日志輸出格式
<settings>
<setting name="mapUnderscoreToCamelCase" value="https://www.cnblogs.com/zzbstudy/p/true"/>
<setting name="logImpl" value="https://www.cnblogs.com/zzbstudy/p/STDOUT_LOGGING"/>
</settings>
<!--注冊Mapper.xml-->
<mappers>
<mapper resource="mapper/BlogMapper.xml"/>
</mappers>
6、插入初始資料
撰寫介面方法
// 新增一個博客
int addBlog(Blog blog);
BlogMapper.xml組態檔撰寫
<insert id="addBlog" parameterType="Blog">
insert into blog (id, title, author, create_time, views) values (#{id}, #{title}, #{author}, #{createTime}, #{views})
</insert>
測驗,插入博客資料:
@Test
public void addBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtil.getId());
blog.setTitle("Mybatis如此簡單");
blog.setAuthor("ZZB");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDUtil.getId());
blog.setTitle("Java如此簡單");
mapper.addBlog(blog);
blog.setId(IDUtil.getId());
blog.setTitle("Spring如此簡單");
mapper.addBlog(blog);
blog.setId(IDUtil.getId());
blog.setTitle("微服務如此簡單");
mapper.addBlog(blog);
sqlSession.close();
}
初始化資料完畢!
測驗結果:

if
需求:根據作者名字和博客名字來查詢博客!如果作者名字為空,那么只根據博客名字查詢,反之,則根據作者名來查詢
1、撰寫介面類
// 查詢博客
List<Blog> queryBlogByIf(Map map);
2、撰寫BlogMapper.xml檔案
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<!--需求1:
根據作者名字和博客名字來查詢博客!
如果作者名字為空,那么只根據博客名字查詢,反之,則根據作者名來查詢
select * from blog where title = #{title} and author = #{author}
-->
<select id="queryBlogByIf" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
3、測驗
@Test
public void queryBlogByIf(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("title", "Java如此簡單");
map.put("author", "ZZB");
List<Blog> blogs = mapper.queryBlogByIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
測驗結果:
Blog{id='01a7d83785c8483cae5d5384772f5c68', title='Java如此簡單', author='ZZB', createTime=Thu Dec 10 20:29:03 CST 2020, views=9999}
這個“where”標簽會知道如果它包含的標簽中有回傳值的話,它就插入一個‘where’,此外,如果標簽回傳的內容是以AND 或OR 開頭的,則它會剔除掉,
Set
需求:更新一個博客
1、撰寫介面方法
// 更新一個博客
int updateBlog(Map map);
2、撰寫BlogMapper.xml組態檔
<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}
</where>
</update>
3、測驗
@Test
public void updateBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("title", "Java如此簡單2");
map.put("author", "zb");
map.put("id", "01a7d83785c8483cae5d5384772f5c68");
mapper.updateBlog(map);
sqlSession.close();
}
測驗結果:

choose
有時候,我們不想用到所有的查詢條件,只想選擇其中的一個,查詢條件有一個滿足即可,使用 choose 標簽可以解決此類問題,類似于 Java 的 switch 陳述句
1、撰寫介面方法
List<Blog> queryBlogByChoose(Map map);
2、撰寫BlogMapper.xml組態檔
<select id="queryBlogByChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null ">
author = #{author}
</when>
<otherwise>
views = #{views}
</otherwise>
</choose>
</where>
</select>
3、測驗
@Test
public void queryBlogByChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("title", "Java如此簡單2");
map.put("author", "ZZB");
List<Blog> blogs = mapper.queryBlogByChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
測驗結果:
注意SQL陳述句

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>
注意:
1、最好基于 單表來定義 sql 片段,提高片段的可重用性;
2、在 sql 片段中不要包括 where,
ForEach
首先將資料庫中的表格id修改為1,2,3,4
需求:查詢 id 分別為1,3,4 的博客資訊
1、撰寫介面方法
// ForEach
List<Blog> queryBlogForeach(Map map);
2、撰寫BlogMapper.xml組態檔
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<!--
collection:指定輸入物件中的集合屬性
item:每次遍歷生成的物件
open:開始遍歷時的拼接字串
close:結束時拼接的字串
separator:遍歷物件之間需要拼接的字串
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
3、測驗
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(3);
ids.add(4);
map.put("ids", ids);
List<Blog> blogList = mapper.queryBlogForeach(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}
測驗結果:
注意SQL陳述句

總結:
其實動態 sql 陳述句的撰寫往往就是一個拼接的問題,為了保證拼接準確,我們最好首先要寫原生的 sql 陳述句出來,然后在通過 mybatis 動態sql 對照著改,防止出錯,多在實踐中使用才是熟練掌握它的技巧,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/232864.html
標籤:Java
上一篇:9 一對多和多對一處理
下一篇:11 快取
