Mybatis框架的动态SQL技术是一种根据特定条件动态拼接sql语句的功能,它存在的意义是为了解决拼接sql语句字符串时的痛点问题
目录
1、if标签
根据条件查询员工信息
我们根据条件查询,有可能会得出多条符合那个条件的结果,类似于模糊查询,所以使用集合接收
映射文件
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp where 1 = 1
<if test="empName != null and empName != ''">
and emp_name = #{empName}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
<if test="gender != null and gender != ''">
and gender = #{gender}
</if>
</select>
问:为什么条件后面要加上1 = 1
假设第一个条件为null不符合条件,那么就会跳过该条件,而往后的条件因为要拼接,前面都有一个关键词and,最后变成
select * from t_emp where and age = #{age}报错
因此需要加上一个恒成立的条件使其变成select * from t_emp where 1 = 1 and empName = #{empName}
测试
此时我们有一个匿名类,其中仅有一个name,那么它进入动态sql后的效果是
成功查询
2、where标签
我们仅使用if的情况下,还需要使用1=1恒成立并在第一个条件前加上and,很麻烦,于是有了<where>标签
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<where>
<if test="empName != null and empName != ''">
emp_name = #{empName}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
<if test="gender != null and gender != ''">
and gender = #{gender}
</if>
</where>
</select>
当第一个条件不符合时where标签会自动消掉前面的and关键字,也不用添加恒成立条件
3、trim标签
我们要拼接字符串,还可以把and拼在最后面,但是在where标签中这样使用会发生报错
因此我们引入trim标签
- prefix | suffix:将trim标签中内容前面或后面添加指定内容
- suffixOverrides | prefixOverrides:将trim标签中内容前面或后面去掉指定内容
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and|or">
<if test="empName != null and empName != ''">
emp_name = #{empName} and
</if>
<if test="age != null and age != ''">
age = #{age} and
</if>
<if test="gender != null and gender != ''">
gender = #{gender} and
</if>
</trim>
</select>
成功引入
注:当我们什么条件都没有的时候,prefixOverrides内并不能指定把where标签去掉,他会在拼接时把where去掉吗
会,若标签中没有内容时,trim标签也会自动关闭,没有内容
当全部条件为null时:
4、choose、when、otherwise标签
相当于if...else if ...else
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<where>
<choose>
<when test="empName != null and empName !=''">
emp_name = #{empName}
</when>
<when test="age != null and age != ''">
age = #{age}
</when>
<when test="gender != null and gender != ''">
gender = #{gender}
</when>
<otherwise>
did = 1
</otherwise>
</choose>
</where>
</select>
这段代码的逻辑就是,寻找有一个符合条件的,有一个就执行并结束,没有就查找did = 1的
测试
四个null,没有一个符合条件,于是就select * from t_emp where did = 1;
符合条件
5、foreach标签 - 批量删除
我们在之前的案例中写过批量删除的功能
不过那时我们使用了${ }字符串拼接,现在想要通过遍历数组实现批量删除
这里使用如果不使用Param注解指定eids,那么遍历的时候就要使用arg与param了,我们在之前的文章中讲过
foreach属性
- collection:需要遍历的数组
- item:数组中的每个元素
- open:foreach标签所循环的所有内容的开始符
- separator:元素分割符
- close:foreach标签所循环的所有内容的结束符
这样拼接后的效果就是
我们再试试拼接成or来实现,将separator赋值为or
效果
6、foreach标签 - 批量增加
映射器
映射文件
<insert id="insertMoreByList">
insert into t_emp values
<foreach collection="emps" item="emp" separator=",">
(null,#{emp.empName},#{emp.age},#{emp.gender},#{emp.email},null)
</foreach>
</insert>
测试
查看sql运行效果
7、sql标签
记录一段sql片段,使用的时候调用即可
<sql id="empColumns">eid,emp_name,age,gender,email</sql>
引用这段sql语句