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>
相关推荐
NE_STOP1 小时前
Vide Coding--AI编程工具的选择
java
码云数智-园园1 小时前
C++20 Modules 模块详解
java·开发语言·spring
程序员黑豆2 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
小宇宙Zz2 小时前
Maven依赖冲突
java·服务器·maven
swordbob2 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
咖啡八杯2 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网2 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记
摇滚侠3 小时前
IDEA 创建 Java 项目 手动整合 SSM 框架
java·ide·intellij-idea
源分享3 小时前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Flittly3 小时前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring