Mybatis 采用@Update,@Insert 进行批量提交的方法

一、方式

update table_name set  db_filed_name='涨三'  where sys_id=1 and sys_name='系统名称'

//对以上sql进行批量更新批量执行
@Update("<script>" +
        "   update user_info" +
        "<trim prefix='set' suffixOverrides=','>" +
        "   user_code=" +
        "<foreach collection='list' item='item' open='case ' close=' end,'>" +
        "   when user_id=#{item.userId} and user_name=#{item.userName} then 
            #{item.userCode}" +
        "</foreach>" +
        "</trim>" +
        "    WHERE" +
        "<foreach collection='list' item='item' open='( ' separator=') or ('close=' )'>" +
        "      user_id=#{item.userId} and user_name=#{item.userName}" +
        " </foreach>" +
        "</script>")
Integer updateUser(List<UserInfoDto> list);

二、解析

1.待更新的数据集是List<User>,其中我们根据User中的userId和userName字段修改user_code 值

2.可以采用动态sql的方式进行批量更新,由于我们采用了动态sql的标签<foreach>,所以需要在sql左外层填加<script></script>进行包裹;

3.这里采用<foreach>进行list遍历。collection 表示集合名;item表示给集合取的别名;open/close表示sql以某个字段开始/结束,我们这边不需要,所以什么都没写;separator表示以什么符号进行分隔。

4.以上动态sql组装完成之后会以以下sql一次性执行:

update table_name set  user_code='涨三'  where user_id=1 and user_name='系统名称1';
update table_name set  user_code='里斯'  where user_id=2 and user_name='系统名称2';
update table_name set  user_code='王五'  where user_id=3 and user_name='系统名称3';
update table_name set  user_code='找钱'  where user_id=4 and user_name='系统名称4';
update table_name set  user_code='孙俪'  where user_id=5 and user_name='系统名称5';
update table_name set  user_code='签章'  where user_id=6 and user_name='系统名称6'
.......

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值