mybatis笔记-mysql批量更新数据

我们在操作一些数据的时候,可能会遇到同时改变被选中的多条数据的的某个值。接下来具体讲一下实现该操作的代码。

parameterType的值有两种情形。一种传过来的值是list,那么他的参数类型就是list,另一种传过来的值是array,那么他的参数类型是array。
foreach的主要参数有,item,index,collection,separator,open,close。
item:循环体中元素的别名,可随便去。该参数必填
index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。
collection:如果传入的是List

<update id="updateBatch" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" separator=";" open="" close="">
  update REGION_CODE set
    isactive =#{item.isactive},
    classname=#{item.classname}
    where id = #{item.id}
</foreach>
</update>

如上所写,运行报错,因为Mybatis映射文件中的sql语句不允许 ; 符号。所以我们按照case when的方式,把代码改改

<update id="batchUpdate" parameterType="java.util.List">
        update r_user set
        isactive =
        <foreach collection="list" item="item" index="index"
            separator=" " open="case id" close="end">
            when #{item.id} then #{item.isactive}
        </foreach>
        ,classname=
        <foreach collection="list" item="item" index="index"
           separator=" " open="case id" close="end">
           when #{item.id} then #{item.classname}
        </foreach>        
        where id in
        <foreach collection="list" item="item" index="index" 
            separator="," open="(" close=")">
            #{item.id}
        </foreach> 
  </update>

批量更新的方法完毕,批量插入数据,批量删除数据的实现方式也大同小异。就不再赘述了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值