10.动态SQL
10.1 简介
什么是动态SQL:
- 动态SQL是指根据==不同的查询条件,拼接生成不同的Sql语句==
简介:
-
MyBatis 的强大特性之一便是它的动态 SQL
-
如果你有使用 JDBC 或其它类似框架的经验,你 就能体会到根据不同条件拼接 SQL 语句的痛苦:
- 拼接是要确保不能忘记 添加必要的空格
- 第一个查询条件不要and
where id=1 and name=“zhangsan” and password=“123456”
- 去掉列名最后一个列名的逗号
insert into user(id,name,value) values(1,”zhangsna”,”123456)
update user set name=”zhangsan2”,password=”123” where id=1
-
动态sql元素和 JSTL标签类似;
-
复杂的SQL语句,往往需要拼接。而拼接SQL稍微不注意,由于引号,空格等的缺失可能都会导致错误。
解决办法:
使用MyBatis的动态SQL,通过if
where,set,trim
foreach
choose,when,otherwise
等标签,可以组合成非常灵活的SQL语句,从而在提高SQL语句的准确性的同时,也大大提高了开发人员的效率。
10.2 搭建环境
新建一个数据库表: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.创建一个maven基础工程
2.IDutils工具类
使用UUID创建唯一id
IDUtils:
public class IDUtils {
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
3.实体类的编写
Blog:
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
4.编写Mapper接口及xml文件
BlogMapper:
public interface BlogMapper {
}
BlogMapper.xml:
<?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.dao.BlogMapper">
</mapper>
5.mybatis核心配置文件,下划线命名 驼峰命名自动转换
<settings>
<!--下划线命名 驼峰命名自动转换-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--注册Mapper.xml-->
<mappers>
<mapper class="com.kuang.dao.BlogMapper"/>
</mappers>
6.初始化接口数据
编写接口:
//新增一个博客
int addBlog(Blog blog);
Mapper.xml:
<insert id="addBlog" parameterType="Blog">
insert into mybatis.blog (id,title,author,create_time,views)
values (#{id},#{title},#{author},#{createTime},#{views});
</insert>
test:初始化博客数据
@Test
public void addInitBlog(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = new Blog();
blog.setId(IDUtils.getId());
blog.setTitle("Mybatis如此简单");
blog.setAuthor("狂神说");
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);
session.commit();
session.close();
}
10.3 if标签
应用场景:
根据条件append查询条件,拼接SQL
需求:根据作者名字author和博客名字title来查询博客:
- 如果author和title都为空,查询全部博客
- author不为空,title为空,查询所有属于author的博客
- author为空,title不为空,查询指定博客名字的博客
- author和title都不为空,查询符合两者条件的博客
1.编写接口类:
//需求1
List<Blog> queryBlogIf(Map map);
2.编写Mapper.xml中SQL语句
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from `blog` where
<if test="author!=null">
author=#{author}
</if>
<if test="title!=null">
and title=#{title}
</if>
</select>
3.测试
@Test
public void test(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Map<String,Object> map=new HashMap<String, Object>();
map.put("author","狂神说");
map.put("title","Mybatis如此简单");
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
session.close();
}
问题:
当author为null,title不为空时,select语句为:select * from blog where and title=#{title}
,这是错误的SQL语句。如何解决呢?采用下面where标签;
10.4 where标签
应用场景:
- 如果查询条件有返回值,就插入where;没有查询条件不插入where;
- 如果第一个查询条件前有and,就去除该and
修改上面的SQL语句:
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from `blog`
<where>
<if test="author!=null">
author=#{author}
</if>
<if test="title!=null">
and title=#{title}
</if>
</where>
</select>
set标签
应用场景:
- update操作,尾部 最后一个逗号
,
剔除 - 当author不为null,title为null时,造成错误: SQL尾部多了一个逗号
update blog set author=#{author},
编写Mapper.xml中SQL语句
<update id="updateBlog" parameterType="map">
update `blog`
<set>
<if test="author!=null">
author=#{author},
</if>
<if test="title!=null">
title=#{title}
</if>
</set>
where id=#{id}
</update>
trim标签
10.5 foreach标签
应用场景:
- **对应于
select * from blog where id in (1,2,3,4)
**
1.编写接口类:
List<Blog> queryBlogForeach(Map map);
2.编写Mapper.xml中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="idList" item="id" open="(" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
3.测试
@Test
public void test(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Map<String,Object> map=new HashMap<String, Object>();
List<String> idList=new ArrayList<String>();
idList.add("ae52b845132a4a7190d4c3e192265fd2");
map.put("idList",idList); //List是map的一个属性
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
session.commit();
session.close();
}
10.6 choose、when、otherwise标签
应用场景:
- 有时候我们不想用所有的查询条件,只想选择其中一个,查询条件有一个满足即可
- 使用choose,类似switch语句,前面的优先匹配优先级更高
1.编写接口类:
List<Blog> queryBlogChoose(Map map);
2.编写Mapper.xml中SQL语句
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="author!=null">
author=#{author}
</when>
<when test="title!=null">
title=#{title}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
3.测试
@Test
public void test(){
SqlSession session = MybatisUtils.getSqlSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Map<String,Object> map=new HashMap<String, Object>();
map.put("title","Java如此简单2");
map.put("author","狂神说2");
map.put("views",9999);
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
session.commit();
session.close();
}
10.7 提取SQL片段
有时候可能某个sql语句我们用的特别多,为了增加代码的复用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。
提取SQL片段:
<sql id="if-title-author">
<if test="author!=null">
author=#{author}
</if>
<if test="title!=null">
and title=#{title}
</if>
</sql>
引用SQL片段:
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from `blog`
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace-->
<include refid="if-title-author"/>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>
注意:
- 最好基于单表定义sql片段,提高片段的可重用性
- 在sql片段中不要包括where
动态SQL小结:
- 动态SQL语句的编写往往就是一个拼接的问题
- 为了保证拼接准确,最好先写出原生的sql语句
- 然后再通过mabatis动态SQL对照修改,防止出错