简介
动态SQL就是根据不同的条件生成不同的SQL语句
所谓的动态SQL本质还是SQL语句,只是我们可以在SQL里面,去执行一个逻辑代码。
动态SQL就是在拼接SQL语句,只要能保证SQL的正确性,按照SQL的格式,排列组合就可以了。
搭建环境
工具类IDUtils.java
public class IDUtils {
/**
* 获取随机ID
* @return
*/
public static String getID(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
where、if
if会根据test条件,来决定是否拼接SQL
where则会根据map中的数据,会自动去除自身以及子句的and或or。
<select id="queryBlog" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
choose、when、otherwise
choose、when、otherwise相当于Java中的Switch
按照先后顺序匹配对应的条件
<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>
update、set
编写update语句时,中间的为数据库字段赋值需要在设置完追加逗号,最后一个不需要
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>
trim
可以自定义去除字符的标签
<!--
where标签的本质
prefix 指定的值
prefixOverrides 替换前缀
-->
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
<!--
set 标签的本质
suffixOverrides 替换后缀
-->
<trim prefix="SET" suffixOverrides=",">
...
</trim>
SQL片段
提取公共SQL,使用时只需引用对应片段的id即可,可以实现代码的复用
<!--
id sql片段名
-->
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<!--
使用include标签引用
refid 要引用的片段名
-->
<select id="queryBlog" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
PS:
- 最好基于单表来定义SQL片段
- 不要存在where标签
foreach
<!--
item 集合项
index 索引
collection 集合
open 开头
separartor 分隔符
close 结尾
-->
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach item="id" collection="ids" open="and (" separator="or" close=") ">
id = #{id}
</foreach>
</where>
</select>