Mybatis 实现多条件、多值批量更新

一、SQL CASE WHEN

  Oracle、MySql并没有提供直接的方法来实现批量更新,但是可以用点小技巧来实现。这里使用了case when来实现批量更新。

  例如:

1 UPDATE demo_table SET
2     status = CASE id
3         WHEN 1 THEN 3
4         WHEN 2 THEN 4
5         WHEN 3 THEN 5
6     END
7 WHERE id IN (1,2,3)

  这个SQL语句的作用是根据条件更新demo_table表的status字段:

  1. 如果id=1,则status更新为3;
  2. 如果id=2,则status更新为4;
  3. 如果id=3,则status更新为5。

  即是将条件语句写在了一起,提高SQL执行效率。

二、Mybatis

单个条件字段批量更新:

 1 <update id="updateBatch" parameterType="java.util.List">
 2     update demo_table
 3     <trim prefix="set" suffixOverrides=",">
 4         <trim prefix="status =case" suffix="end,">
 5              <foreach collection="list" item="item" index="index">
 6                  <if test="item.status !=null ">
 7                      when id=#{item.id} then #{item.status}
 8                 </if>                    
 9              </foreach>
10         </trim>
11     </trim>
12     where id in
13     <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
14         #{item.id,jdbcType=BIGINT}
15     </foreach>
16 </update>

多个条件字段批量更新:

 1 <update id="updateBatch" parameterType="java.util.List">
 2     update CLIENT_INFO
 3     <trim prefix="set" suffixOverrides=",">
 4         CARD_NUM=
 5         <foreach collection="list" item="item" open="case " close=" end,">
 6             when ID_CARD_NO=#{item.idCardNo} and STATUS=4 then #{item.cardNum}
 7         </foreach>
 8         create_time =
 9         <foreach collection="list" item="item" open="case " close=" end,">
10           when field2=#{item.field2} and field3=#{item.field3} then
11           <choose>
12             <when test="item.createTime!=null">
13               #{item.createTime}
14             </when>
15             <otherwise>now()</otherwise>
16           </choose>
17         </foreach>
18     </trim>
19     WHERE
20     <foreach collection="list" item="item" open="( " separator=") or (" close=" )">
21       ID_CARD_NO=#{item.idCardNo} and field3=#{item.field3} 
22     </foreach>
23 </update>

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁凤财

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值