
在MyBatis中,动态SQL是一项非常强大的功能,允许我们根据不同的条件生成不同的SQL语句。本文将详细介绍动态SQL的各种用法,并通过代码示例演示如何灵活运用这些功能。
动态SQL是MyBatis中一个核心的功能,它可以帮助我们在编写SQL时更加灵活,根据不同的情况生成不同的SQL语句,从而满足各种复杂的业务需求。
在开始之前,我们需要先搭建好环境,并准备好相应的数据表和实体类。这样才能更好地演示动态SQL的功能。
我们以一个博客系统为例,创建一个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.导包
2.编写配置文件
3.工具包
//抑制警告
@SuppressWarnings("all")
public class IDutils {
public static String getId(){
return UUID.randomUUID().toString().replace("-","");
}
}我们创建一个Blog实体类,用于映射blog表的数据结构。
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}插入数据
@Test
public void addInitBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog(IDutils.getId(),"Mybatis如此简单","狂神说",new Date(),9999);
mapper.addBlog(blog);
blog = new Blog(IDutils.getId(),"Java如此简单","狂神说",new Date(),1000);
mapper.addBlog(blog);
blog = new Blog(IDutils.getId(),"Spring如此简单","狂神说",new Date(),9999);
mapper.addBlog(blog);
blog = new Blog(IDutils.getId(),"微服务如此简单","狂神说",new Date(),9999);
mapper.addBlog(blog);
sqlSession.close();
}动态SQL中最基本的功能之一就是条件判断,我们可以使用<if>标签根据条件动态生成SQL语句。
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>@Test
public void queryBlogIF() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("title", "Mybatis如此简单");
// map.put("author", "狂神说");
List<Blog> blogList = mapper.queryBlogIF(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}类似于Java中的switch语句,<choose>标签允许我们从多个条件中选择一个执行。
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.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>@Test
public void queryBlogChoose() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("title", "Mybatis如此简单2");
// map.put("author", "狂神说");
// map.put("views", 100);
mapper.updateBlog(map);
sqlSession.close();
}<trim>标签可以用来修饰SQL语句的where和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>@Test
public void updateBlog() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<>();
// map.put("title", "Mybatis如此简单");
// map.put("author", "狂神说");
List<Blog> blogList = mapper.queryBlogChoose(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}有时候,我们会发现某些SQL片段会被多次使用,这时可以将这些公共部分抽取出来,方便重用。
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="if-title-author" />
</where>
</select><foreach>标签可以用来循环遍历集合,并动态生成SQL语句中的一部分。


<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);
HashMap<String, Object> map = new HashMap<>();
ArrayList<String> ids = new ArrayList<>();
ids.add("d97ca9c234df463e950f252d22fb5f85");
ids.add("4cfe16fcebb145f894b6ec9033f8ae33");
ids.add("5d3adbfea47b4493bc086cf8dbb8998a");
map.put("ids", ids);
List<Blog> blogList = mapper.queryBlogForeach(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}动态SQL是MyBatis中非常重要的一个功能,通过灵活运用动态SQL,我们可以轻松地构建出符合不同条件的SQL语句,从而满足各种业务需求。
随着MyBatis的不断发展,相信动态SQL功能会变得越来越强大,为我们带来更多便利。我们可以期待在未来的版本中看到更多新功能的加入。
通过本文的学习,相信你对MyBatis中的动态SQL功能有了更深入的了解。希望本文能够帮助你更好地应用动态SQL,提升开发效率!