MyBatis动态SQL
# 动态SQL❌
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一些逻辑代码
# 1、if
动态 SQL 通常要做的事情是有条件地包含 where 子句的一部分。比如:
【示例】ArticleMapper.java
public interface ArticleMapper {
List<Article> selectArticleByTitle(Article article);
}
1
2
3
4
5
2
3
4
5
【示例】Mapper.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.singerw.mapper.ArticleMapper">
<select id="selectArticleByTitle" resultType="article" parameterType="article">
select * from artilce where status = 1
<if test="title !=null">
and title like #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
</mapper>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 2、choose(when, otherwise)
有些时候,我们不想用到所有的条件语句,而只想从中择其一二。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
【示例】Mapper.xml
<select id="queryBlogChoose" parameterType="map" resultType="com.rui.pojo.Blog">
select * from mybatis.bolg
<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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
【示例】Mapper.xml
1
# 3、trim(where, set)
【示例】Mapper.xml
select * from mybatis.bolg
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
【示例】Mapper.xml
<update id="updateBlog" parameterType="map">
update mybatis.bolg
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author},
</if>
</set>
where id = #{id}
</update>
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 4、foreach
可以做查询和删除还要批量删除。
【示例】ArticleMapper.xml
select * from user where 1=1 and
<foreach item="id" index="index" collection="ids"
open="(" separator="or" close=")">
#{id}
</foreach>
(id=1 or id=2 or id=3)
1
2
3
4
5
6
7
2
3
4
5
6
7
【示例】ArticleMapper.xml
<!--
select * from mybatis.bolg where 1=1 and (id=1 or id=2 or id=3)
我们现在传递一个万能的map,这个map中可以存在一个map
-->
<select id="queryBlogForeach" parameterType="map" resultType="com.rui.pojo.Blog">
select * from mybatis.bolg
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 5、SQL片段
有的时候,我们可能会将一些公共的部分抽取出来,方便复用!
使用SQL标签抽取公共的部分
<sql id="if-title-author"> <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </sql>
1
2
3
4
5
6
7
8在需要使用的地方使用Include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="com.rui.pojo.Blog"> select * from mybatis.bolg <where> <include refid="if-title-author"></include> </where> </select>
1
2
3
4
5
6注意事项:
- 最好基于单表来定义SQL片段!
- 不要存在where或者set标签,片段里尽量只有if就好了
编辑 (opens new window)