MyBatis动态SQL

本文介绍了MyBatis中如何通过动态SQL(if、when-otherwise、foreach)实现条件灵活查询,展示了如何通过XML映射和代理模式简化SQL编写,以及在if条件、选择分支和批量删除场景的应用实例。
摘要由CSDN通过智能技术生成

MyBatis封装了JDBC通过Mapper代理的方式,以前繁琐的操作通过“属性与字段映射”就简单化解。

一、动态Sql

Sql语句会随着用户的输入或者外部条件的变化而变化,则称之为动态Sql

1、if和where

因为采用了Mapper代理开发,我们可以通过写xml的形式来编写我们的SQL,在原有的Mapper文件里我们进行如下改造,使得sql语句可以实现的功能更加多样化,以适应平时业务中的各种情况

<select id="selByCondition" resultMap="rm">
    select *
    from mybatis  
    <where>
    <if test="status !=null">
       and STATUS=#{STATUS}
    </if>
    <if test="companyName !=null and companyName !=''">
    and company_name like #{companyName}
    </if>
    <if test="bracdName !=null and bracdName !=''">
    and bracd_name like #{bracdName}
    </if>
    </where>
</select>

where标签可以自动帮我们去掉and或者or,这样,不管查询的条件怎么变,跟着这个逻辑流程走就不会出现SQL语法毛病而导致查询不出来的毛病啦,因为null的情况已经被if所过滤掉了

2.choose-when-ortherwise

对于从多个条件中选择一个的单条件查询的场景,利用分支嵌套就可以实现动态选择单条件:

在MyBatis的Mapper代理中,choose相当于switch,when相当于case

<select id="selByCondition2" resultMap="rm">
    select *
    from mybatis where
    <choose>
        <when test="status !=null">
            STATUS=#{STATUS}
        </when>
        <when test="companyName !=null and companyName !=''">
            company_name like #{companyName}
        </when>
        <when test="bracdName !=null and bracdName !=''">
            bracd_name like #{bracdName}
        </when>
        <otherwise>1=1</otherwise>
    </choose>
</select>

与多条件查询不同的是,SQL语句中只会有一个分支生效

3.foreach

对于批量删除的场景,传统的方法是通过in关键字结合占位符来确定

where id in (?,?,?)

所以使用了@Param注解改变了map集合中默认的key

void deleteById(@Param("ids") int[] id);

于是MyBatis中的<foreach>解决了这一麻烦:

本质是通过遍历的形式,批量删除的数据是由id数组或者集合来决定,collection属性决定了要遍历哪个数组/集合,item属性则来存放选出的元素,并把它放在占位符里,separator属性表示分隔符

<delete id="deleteById">
    delete frpm mybatis where id in
    <foreach collection="ids" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>;
</delete>

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值