mybatis批量更新

mybatis批量更新

1.常见的批量更新(生成多条执行语句)

<update id="updateBatch"  parameterType="java.util.List">  
    <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update course
        <set>
            name=${item.name}
        </set>
        where id = ${item.id}
    </foreach>      
</update>

这种写法需要给数据库添加配置allowMultiQueries=true

2.一条语句执行批量更新操作

<update id="updateBatch" parameterType="java.util.List">
    update mydata_table 
    set  status=
    <foreach collection="list" item="item" index="index" 
        separator=" " open="case ID" close="end">
        when #{item.id} then #{item.status}
    </foreach>
    where id in
    <foreach collection="list" index="index" item="item" 
        separator="," open="(" close=")">
        #{item.id,jdbcType=BIGINT}
    </foreach>
 </update>

生成的sql如下:

    update mydata_table 
    set status = 
    --此处应该是<foreach>展开值
    case id
        when id = #{item.id} then #{item.status}
        ...
    end
    where id in (...);

第一种方法是用传统方式生成的多条SQL语句,执行效率相对较低。第二种方法是巧妙使用case when的语法完成的一条语句实现的批量更新的操作,执行效率相对较快。使用起来也比较方便。

参考文献

  1. https://blog.csdn.net/xyjawq1/article/details/74129316
  2. https://blog.csdn.net/qq_40558766/article/details/89966773
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值