动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。
MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分
比如:
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = 'ACTIVE'
<if test="title != null">
AND title like #{title}
if>
select>
这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果
现在我们来举一个使用IF查询的实例:
BlogMapper.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.imustctf.dao.BlogMapper">
<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>
mapper>
测试类:
之传入一个title参数的时候,会匹配title进行查询:
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Raspberry");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
结果:
Blog(id=64, title=Raspberry, author=陶子韬, createTime=Thu Dec 21 08:39:41 CST 2017, views=862)
Blog(id=60, title=Raspberry, author=薛震南, createTime=Sat Sep 03 19:56:49 CST 2016, views=70)
Blog(id=43, title=Raspberry, author=郭岚, createTime=Sat Sep 16 01:06:40 CST 2006, views=901)
...
再传入一个author参数,会匹配title和author进行查询:
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("author","陶子韬");
map.put("title","Raspberry");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
结果:
Blog(id=64, title=Raspberry, author=陶子韬, createTime=Thu Dec 21 08:39:41 CST 2017, views=862)
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG
不用于IF的是choose只会匹配一个条件进行查询🐚
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = 'ACTIVE'
<choose>
<when test="title != null">
AND title like #{title}
when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
when>
<otherwise>
AND featured = 1
otherwise>
choose>
select>
现在我们来举一个使用choose、when、otherwise查询的实例:
BlogMapper.xml:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.imustctf.dao.BlogMapper">
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from blog
<where>
<choose>
<when test="title != null">
and title = #{title}
when>
<when test="author != null">
and author = #{author}
when>
<otherwise>
and views >= 900
otherwise>
choose>
where>
select>
mapper>
测试类开发:
我们传入一个title参数时,会匹配title进行查询:
@Test
public void test2() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Kiwi");
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
---------------------------------
Blog(id=46, title=Kiwi, author=侯宇宁, createTime=Tue Nov 01 02:07:02 CST 2011, views=470)
Blog(id=1, title=Kiwi, author=谢睿, createTime=Wed Jan 05 12:25:54 CST 2022, views=513)
Blog(id=92, title=Kiwi, author=余秀英, createTime=Fri May 22 17:07:10 CST 2020, views=433)
传入两个参数时,依然只会匹配一个title进行查询:
@Test
public void test2() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title","Kiwi");
map.put("author","侯宇宁");
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
-------------------------------------
Blog(id=46, title=Kiwi, author=侯宇宁, createTime=Tue Nov 01 02:07:02 CST 2011, views=470)
Blog(id=1, title=Kiwi, author=谢睿, createTime=Wed Jan 05 12:25:54 CST 2022, views=513)
Blog(id=92, title=Kiwi, author=余秀英, createTime=Fri May 22 17:07:10 CST 2020, views=433)
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
例如在第一个例子中:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.imustctf.dao.BlogMapper">
<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>
mapper>
if语句包含在where中,可以自动去除AND或者OR
用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},if>
<if test="password != null">password=#{password},if>
<if test="email != null">email=#{email},if>
<if test="bio != null">bio=#{bio}if>
set>
where id=#{id}
update>
这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
trim>
和 set 元素等价的自定义 trim 元素为:
<trim prefix="SET" suffixOverrides=",">
...
trim>
对于常用的SQL内容,我们可以保存为SQL片段,以重复利用:
例如:
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.imustctf.dao.BlogMapper">
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
if>
<if test="author != null">
and author = #{author}
if>
sql>
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="if-title-author"/>
where>
select>
mapper>
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
例如:我们想要编写如下的SQL语句:
select * from blog where 1=1 and (id = 1 or id = 2 or id = 3)
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="top.imustctf.dao.BlogMapper">
<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>
mapper>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值🪸
现在可以来测试一下效果了:
@Test
public void test3() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
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();
}
------------------------------------------------------
Blog(id=1, title=Kiwi, author=谢睿, createTime=Wed Jan 05 12:25:54 CST 2022, views=513)
Blog(id=2, title=Raspberry, author=魏秀英, createTime=Sat Dec 09 11:07:58 CST 2006, views=426)
Blog(id=3, title=Kiwi se, author=邵詩涵, createTime=Sun Mar 19 15:42:01 CST 2000, views=32)