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>
相关推荐
apocelipes5 小时前
golang unique包和字符串内部化
java·python·性能优化·golang
Full Stack Developme5 小时前
java.text 包详解
java·开发语言·python
刘梦凡呀6 小时前
C#获取钉钉平台考勤记录
java·c#·钉钉
盒马coding6 小时前
第19节-非规范化数据类型-Composite-types
数据库·postgresql
best_virtuoso6 小时前
PostgreSQL 常见数组操作函数语法、功能
java·数据结构·postgresql
yudiandian20146 小时前
02 Oracle JDK 下载及配置(解压缩版)
java·开发语言
-雷阵雨-7 小时前
MySQL——桥梁JDBC
数据库·mysql·oracle
亿坊电商7 小时前
在PHP框架里如何进行数据库连接?
数据库·oracle·php
满昕欢喜7 小时前
SQL Server从入门到项目实践(超值版)读书笔记 28
数据库·sql·sqlserver
楚韵天工7 小时前
宠物服务平台(程序+文档)
java·网络·数据库·spring cloud·编辑器·intellij-idea·宠物