mybatis 实现批量更新的三种方式

注:Mybatis实现批量更新有三种方式,分别是使用foreach标签、使用SQL的case when语句和使用动态SQL的choose语句。具体实现方法如下:

1:使用foreach标签

sql 复制代码
<update id="batchUpdate" parameterType="java.util.List">
  update user set name=#{name}, age=#{age} where id=#{id}
  <foreach collection="list" item="item" index="index" separator=";">
    update user set name=#{item.name}, age=#{item.age} where id=#{item.id}
  </foreach>
</update>

2:使用SQL的case when语句

sql 复制代码
<update id="batchUpdate" parameterType="java.util.List">
  update user set name = case id
    <foreach collection="list" item="item" index="index" separator=" ">
      when #{item.id} then #{item.name}
    </foreach>
  end,
  age = case id
    <foreach collection="list" item="item" index="index" separator=" ">
      when #{item.id} then #{item.age}
    </foreach>
  end
  where id in
  <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
    #{item.id}
  </foreach>
</update>

3:使用动态SQL的choose语句

sql 复制代码
<update id="batchUpdate" parameterType="java.util.List">
  <foreach collection="list" item="item" index="index" separator=";">
    <choose>
      <when test="item.name != null and item.age != null">
        update user set name=#{item.name}, age=#{item.age} where id=#{item.id}
      </when>
      <when test="item.name != null">
        update user set name=#{item.name} where id=#{item.id}
      </when>
      <when test="item.age != null">
        update user set age=#{item.age} where id=#{item.id}
      </when>
    </choose>
  </foreach>
</update>
相关推荐
小阳拱白菜8 分钟前
java异常学习
java
FrankYoou1 小时前
Jenkins 与 GitLab CI/CD 的核心对比
java·docker
计算机毕设定制辅导-无忧学长2 小时前
西门子 PLC 与 Modbus 集成:S7-1500 RTU/TCP 配置指南(一)
服务器·数据库·tcp/ip
麦兜*2 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了2 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
天河归来2 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
程序员柳2 小时前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
weixin_478689762 小时前
十大排序算法汇总
java·算法·排序算法
码荼2 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud
梦在深巷、2 小时前
MySQL/MariaDB数据库主从复制之基于二进制日志的方式
linux·数据库·mysql·mariadb