文章目录
- 搭建环境
- IF(重点)
- choose (when, otherwise)
- trim、where、set
- where(重点)
- set(重点)
- SQL片段
- 注意事项:
- Foreach
- 案例
- 总结
什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
所谓的动态SQL,本质上还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
- if(重点)
- choose (when, otherwise)
- trim (where, set)
- foreach
搭建环境
数据库
CREATE TABLE `mybatis`.`blog` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '博客id',
`title` varchar(30) NOT NULL COMMENT '博客标题',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` datetime(0) NOT NULL COMMENT '创建时间',
`views` int(30) NOT NULL COMMENT '浏览量',
PRIMARY KEY (`id`)
)
创建一个基础工程
- 导包
- 编写配置文件
- 编写实体类
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;// 属性名和字段名不一致
private int views;
}
- 编写实体类对应Mapper接口和Mapper.xml文件
IF(重点)
需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
编写接口类
//查询博客
List<Blog> queryBlogIF(Map map);
编写SQL语句
<insert id="addBolg" parameterType="blog">
insert into blog (id, title, author, create_time, views)
values (#{id}, #{title}, #{author}, #{createTime}, #{views});
</insert>
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select *
from blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
测试
@Test
public void queryBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","java");
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
======
Blog(id=2, title=java, author=狂神说, createTime=Wed Apr 13 08:00:00 CST 2016, views=1000)
这样写我们可以看到,如果 author 等于 null,那么查询语句为 select from user where title=#{title},但是如果title为空呢?那么查询语句为 select from user where and author=#{author},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句!
choose (when, otherwise)
choose:选择
when:什么时候
otherwise:其他
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select *
from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != author">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
@Test
public void queryBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","java");
map.put("author","狂神说");
map.put("views",9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
=========
Blog(id=2, title=java, author=狂神说, createTime=Wed Apr 13 08:00:00 CST 2016, views=1000)
trim、where、set
where(重点)
修改上面的SQL语句;
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select *
from blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
@Test
public void queryBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","java");
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。
此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。【这是我们使用的最多的案例】
set(重点)
同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
编写接口方法
//更新博客
int updateBlog(Map map);
xml
<insert 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}
</insert>
测试
@Test
public void updateBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// map.put("title","java2");
map.put("author","狂神说4");
map.put("id",1);
// map.put("views",9999);
mapper.updateBlog(map);
sqlSession.close();
}
===================
==> Preparing: update blog SET author = ? where id = ?
==> Parameters: 狂神说4(String), 1(Integer)
<== Updates: 1
逻辑:
- if:判断
- where:保证sql尽量不出问题
- set:保证sql尽量不出问题
- choose
- when
SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便服用!
- 使用SQL标签抽取公共部分可
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
- 在需要使用的地方使用Include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select *
from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
- 测试
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// map.put("title","java");
map.put("author","狂神说");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
==========================
Blog(id=2, title=java, author=狂神说, createTime=Wed Apr 13 08:00:00 CST 2016, views=1000)
Blog(id=3, title=Spring, author=狂神说, createTime=Wed Apr 13 08:00:00 CST 2016, views=9999)
Blog(id=4, title=微服务, author=狂神说, createTime=Wed Apr 13 08:00:00 CST 2016, views=9999)
注意事项:
- 最好基于单标来定义SQL片段!
- 不要存在where标签
Foreach
只查123
select * from user where 1=1 and
<foreach item="id" collection="ids"
open="(" separator="or" close=")">
#{id}
</foreach>
(id = 1 or id = 2 or id = 3)
需要的:传入的集合语句,遍历的每一项。
案例
查询1,2,3号记录的博客
数据库
接口
//查询1,2,3号记录的博客
List<Blog> queryBlogForeach(Map map);
xml
<!--
select * from blog where 1=1 and (id = 1 or id = 2 or id = 3)
传递一个万能的map,这map中可以存在一个集合!collection ,
item:从集合遍历的每一项的名字
open:以什么开始
close:以什么结束
separator:分隔符
-->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
测试
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
//传入map
HashMap map = new HashMap();
//拿到map里边的key 准备一个ids
ArrayList<Integer> ids = new ArrayList<>();
//传数字
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
结果
==> Preparing: select * from mybatis.blog WHERE ( id = ? or id = ? or id = ? )
==> Parameters: 1(Integer), 2(Integer), 3(Integer)
<== Columns: id, title, author, create_time, views
<== Row: 1, Mybatis, 狂神说4, 2016-04-13 00:00:00, 9999
<== Row: 2, java, 狂神说, 2016-04-13 00:00:00, 1000
<== Row: 3, Spring, 狂神说, 2016-04-13 00:00:00, 9999
<== Total: 3
Blog(id=1, title=Mybatis, author=狂神说4, createTime=Wed Apr 13 08:00:00 CST 2016, views=9999)
Blog(id=2, title=java, author=狂神说, createTime=Wed Apr 13 08:00:00 CST 2016, views=1000)
Blog(id=3, title=Spring, author=狂神说, createTime=Wed Apr 13 08:00:00 CST 2016, views=9999)
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@568ff82]
Returned connection 90767234 to pool.
总结
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
- 先在Mysql中写出完整的SQL,再对应的去修改成我们的动态SQL实现通用即可
select *
from blog where 1=1 and (id = 1 or id = 2 or id = 3)