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>
相关推荐
wang6021252181 分钟前
FastAPI框架为什么在启动时建表
数据库
男孩李3 分钟前
linux下如何执行postgres数据库的sql文件
数据库·sql·postgresql
zwjapple7 分钟前
MySQL SQL 面试核心考点与注意事项总结
数据库·sql·mysql
乐韵天城8 分钟前
SpringBoot中如何手动开启数据库事务
数据库·spring boot
Knight_AL13 分钟前
Spring AOP 中 JoinPoint 使用指南
java·python·spring
05大叔13 分钟前
Spring Day02
数据库·sql·spring
jmxwzy17 分钟前
点赞系统问题
java·redis·tidb·pulsar
默默前行的虫虫19 分钟前
nicegui中多次调用数据库操作总结
数据库·python
ss27321 分钟前
ThreadPoolExecutor:自定义线程池参数
java·开发语言
鸽鸽程序猿26 分钟前
【Redis】事务
数据库·redis·缓存