7Mybatis动态SQL
动态SQL
1简介
- 什么是动态SQL:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句
- 我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。
- 这就要使用 mybatis 动态SQ
- 在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。
- if
- choose(when,otherwise)
- trim(where,set)
- foreach
2搭建环境
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
//IDUtils
public class IDUtils {
//公司中一般都是获取随机Id
public static String getId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
@Test
public void test(){
System.out.println(IDUtils.getId());
}
}
//Blog
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;//属性名和字段名不一致
private int views;
}
//下面三步用于插入初始数据
//BlogMapper
public interface BlogMapper {
//插入数据
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>
//MyTest
@Test
public void addBlogTest() {
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.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);
sqlSession.commit();
sqlSession.close();
}
3if
- 需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
3.1编写接口类
//BlogMapper
List<Blog> queryBlogIf(Map map);
3.2编写sql语句
<!-- BlogMapper.xml -->
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from blog where 1=1
<if test="title !=null">
and title =#{title}
</if>
<if test="author">
and author=#{author}
</if>
</select>
3.3测试
@Test
public void test2(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Java");
List<Blog> blogs = mapper.queryBlogIf(map);
for(Blog blog:blogs){
System.out.println(blog);
}
sqlSession.close();
}
4Where/choose
- “where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉
- 有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句
4.1编写接口类
//where choose
List<Blog> queryBlogChoose(Map map);
4.2sql语句
<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>
4.3测试
@Test
public void test3(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Java");
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog:blogs) {
System.out.println(blog);
}
sqlSession.close();
}
5Set
- 和where一样,where用在查询操作,这个用在更新操作
5.1编写接口类
//set
int updateBLog(Map map);
5.2sql语句
<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>
5.3测试
@Test
public void test4(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Java改");
map.put("id","1");
int i = mapper.updateBLog(map);
System.out.println(i);
sqlSession.commit();
sqlSession.close();
}
6SQL片段
- 有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用
6.1提取SQL片段
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
6.2引用SQL片段
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<where>
<!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
<include refid="if-title-author"></include>
<!-- 在这里还可以引用其他的 sql 片段 -->
</where>
</select>
6.3注意
- 最好基于 单表来定义 sql 片段,提高片段的可重用性
- 在 sql 片段中不要包括 where
7Foreach
- 需求:我们需要查询 blog 表中 id 分别为1,2,3的博客信息
-
- collection:指定输入对象中的集合属性
- item:每次遍历生成的对象
- open:开始遍历时的拼接字符串
- close:结束时拼接的字符串
- separator:遍历对象之间需要拼接的字符串
7.1编写接口
//查询第123号博客
List<Blog> queryBlogForeach(Map map);
7.2sql语句
<!--foreach
select * from blog where 1=1 and (id=1 or id=2 or id=3)
我们传递一个万能的Map,这map中可以存在一个集合-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
7.3测试
@Test
public void test5(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Java改");
map.put("id","1");
ArrayList<Integer> ids = new ArrayList<>();
map.put("ids",ids);
ids.add(1);
ids.add(2);
ids.add(3);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog:blogs){
System.out.println(blog);
}
sqlSession.commit();
sqlSession.close();
}
8小结
- 其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。多在实践中使用才是熟练掌握它的技巧。

浙公网安备 33010602011771号