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>
相关推荐
RainbowSea9 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea9 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
考虑考虑13 小时前
Jpa使用union all
java·spring boot·后端
用户37215742613514 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
RestCloud14 小时前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud14 小时前
为什么说零代码 ETL 是未来趋势?
数据库·api
浮游本尊15 小时前
Java学习第22天 - 云原生与容器化
java
ClouGence16 小时前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
渣哥16 小时前
原来 Java 里线程安全集合有这么多种
java
间彧16 小时前
Spring Boot集成Spring Security完整指南
java