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>
相关推荐
noravinsc13 分钟前
django.db.models.query_utils.DeferredAttribute object
数据库·django·sqlite
柯34917 分钟前
JVM-类加载机制
java·开发语言·jvm
风雨无阻fywz21 分钟前
java 类的实例化过程,其中的相关顺序 包括有继承的子类等复杂情况,静态成员变量的初始化顺序,这其中jvm在干什么
java·开发语言·jvm
沃野_juededa1 小时前
关于uniapp 中uview input组件设置为readonly 或者disabled input区域不可点击问题
java·前端·uni-app
阿桨3 小时前
【Prometheus-MySQL Exporter安装配置指南,开机自启】
数据库·mysql
红烧柯基4 小时前
解决redis序列号和反序列化问题
java·数据库·redis
小黄人20254 小时前
【KWDB 创作者计划】一款面向 AIoT 的多模数据库实战体验
数据库·云计算·kwdb
wangzhongyudie4 小时前
SQL实战:03之SQL中的递归查询
数据库·hive·sql
API_technology4 小时前
《淘宝 API 数据湖构建:实时商品详情入湖 + Apache Kafka 流式处理指南》
数据库·分布式·数据挖掘·kafka·apache
DDDiccc4 小时前
黑马Redis(四)
数据库·redis·mybatis