动态 SQL 和映射机制

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"&
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值