官方檔案:https://mybatis.org/mybatis-3/zh/dynamic-sql.html
1、介紹
什么是動態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 陳述句的準確性的同 時,也大大提高了開發人員的效率,
2、搭建環境
新建一個資料庫表: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. 物體類撰寫
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"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hang.dao.BlogMapper">
</mapper>
5. mybatis核心組態檔,下劃線駝峰自動轉換
<settings>
<setting name="logImpl" value="https://www.cnblogs.com/wyh518/archive/2023/01/02/STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="https://www.cnblogs.com/wyh518/archive/2023/01/02/true"/>
</settings>
<mappers>
<package name="com.hang.dao"/>
</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 sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtils.getId());
blog.setTitle("Mybatis");
blog.setAuthor("xxx");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDUtils.getId());
blog.setTitle("Java");
mapper.addBlog(blog);
blog.setId(IDUtils.getId());
blog.setTitle("Spring");
mapper.addBlog(blog);
blog.setId(IDUtils.getId());
blog.setTitle("微服務");
mapper.addBlog(blog);
sqlSession.close();
}
初始化資料完畢!
3、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 queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("title","Java");
map.put("author","xxx");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
這樣寫我們可以看到,如果 author 等于 null,那么查詢陳述句為 select * from user where title=#{title}, 但是如果title為空呢?那么查詢陳述句為 select * from user where and author=#{author},這是錯誤的 SQL 陳述句,如何解決呢?請看下面的 where 陳述句!
4、Where
修改上面的SQL陳述句;
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
這個“where”標簽會知道如果它包含的標簽中有回傳值的話,它就插入一個‘where’,此外,如果標簽返 回的內容是以AND 或OR 開頭的,則它會剔除掉,【這是我們使用的最多的案例】
5、Set
同理,上面的對于查詢 SQL 陳述句包含 where 關鍵字,如果在進行更新操作的時候,含有 set 關鍵詞, 我們怎么處理呢?
1. 撰寫介面方法
int updateBlog(Map map);
2. sql組態檔
<!--注意set是用的逗號隔開-->
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
</update>
3. 測驗
@Test
public void updateBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("title","Python");
map.put("id","ff0eeaeb7968422caf7680ddab26b740");
mapper.updateBlog(map);
sqlSession.close();
}
6、choose陳述句
有時候,我們不想用到所有的查詢條件,只想選擇其中的一個,查詢條件有一個滿足即可,使用 choose 標簽可以解決此類問題,類似于 Java 的 switch 陳述句
1. 撰寫介面方法
List<Blog> queryBlogChoose(Map map);
2. sql組態檔
<select id="queryBlogChoose" resultType="blog" parameterType="map">
select * from mybatis.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 queryBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("views",9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
7、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 mybatis.blog
<where>
<!-- 參考 sql 片段,如果refid 指定的不在本檔案中,那么需要在前面加namespace-->
<include refid="if-title-author"/>
<!-- 在這里還可以參考其他的 sql 片段 -->
</where>
</select>
注意:
①、最好基于 單表來定義 sql 片段,提高片段的可重用性
②、在 sql 片段中不要包括 where
8、Foreach
將資料庫中前三個資料的id修改為1,2,3;
需求:我們需要查詢 blog 表中 id 分別為1,2,3的博客資訊
1. 撰寫介面
List<Blog> queryBlogForeach(Map map);
2. 撰寫SQL陳述句
<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>
3. 測驗
@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 對照著改,防止出錯,多在實踐中使用才是熟練掌握它的技巧
本文來自博客園,作者:腹白,轉載請注明原文鏈接:https://www.cnblogs.com/wyh518/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/541068.html
標籤:其他
下一篇:1.2復習了一下MySQL的索引
