1、动态 SQL
1.1、if
用于条件判断,test 属性用于指定判断条件,为了拼接条件,在 SQL 语句后面强行添加 1 = 1 的恒成立条件。
public interface EmpMapper4 {
/*
查询所有的员工数据
如果传递员工姓名就根据员工姓名查询
如果传递员工薪资就根据员工薪资查询
如果两个条件都存在,就根据员工姓名与员工薪资一起查询
*/
List<Emp> selectEmp(@Param("ename") String ename, @Param("sal") Double sal);
}
<select id="selectEmp" resultType="Emp">
select * from emp where 1 = 1
<if test="ename != null and ename != ''"> and ename = #{ename} </if>
<if test="sal != null and sal != 0"> and sal = #{sal} </if>
</select>
List<Emp> list = mapper4.selectEmp(null, 1250.00);
1.2、where
用于管理 where 子句,好处:
-
内部如果存在满足要求的子句,就拼接一个 where 关键字,不存在就不拼接
-
自动删除多余的第一个 and 关键字
public interface EmpMapper4 {
/*
查询所有的员工数据
如果传递员工姓名就根据员工姓名查询
如果传递员工薪资就根据员工薪资查询
如果两个条件都存在,就根据员工姓名与员工薪资一起查询
*/
List<Emp> selectEmp(@Param("ename") String ename, @Param("sal") Double sal);
}
<select id="selectEmp" resultType="Emp">
select * from emp
<where>
<if test="ename != null and ename != ''"> and ename = #{ename} </if>
<if test="sal != null and sal != 0"> and sal = #{sal} </if>
</where>
</select>
List<Emp> list = mapper4.selectEmp(null, null);
1.3、choose...when...otherwise
等同于 switch...case...
public interface EmpMapper4 {
/*
存在员工姓名根据姓名查询
存在员工薪资根据薪资查询
都存在,根据姓名查询
都不存在,查询所有
* */
List<Emp> selectEmp2(@Param("ename") String enaem, @Param("sal") Double sal);
}
<select id="selectEmp2" resultType="Emp">
select * from emp
<where>
<choose>
<when test="ename != null and ename != ''"> and ename = #{ename} </when>
<when test="sal != null and sal != 0"> and sal = #{sal} </when>
<otherwise> and 1=1 </otherwise>
</choose>
</where>
</select>
List<Emp> list = mapper4.selectEmp2(null, 1250.00);
1.4、set
用于维护 update 语句中的 set 子句,功能如下:
-
满足条件时,会自动添加 set 关键字
-
会去除 set 子句中多余的逗号
-
不满足条件时,不会生成 set 关键字
public interface EmpMapper4 {
/*
* 根据员工编号修改员工名称
* 根据员工编号修改员工薪资
* 根据员工编号修改员工名称+薪资
* */
int updateEmp(@Param("empno") int empno, @Param("ename") String ename, @Param("sal") Double sal);
}
<update id="updateEmp">
update emp
<set>
empno = #{empno}, <!-- 防止所有条件不成立时的语法错误 -->
<if test="ename != null and ename != ''"> ename = #{ename}, </if>
<if test="sal != null and sal != 0"&