mybatis 实现批量更新的三种方式

注:Mybatis实现批量更新有三种方式,分别是使用foreach标签、使用SQL的case when语句和使用动态SQL的choose语句。具体实现方法如下:

1:使用foreach标签

<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语句

<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语句

<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>

相关推荐

  1. mybatis 实现批量更新方式

    2023-12-07 17:34:05       29 阅读
  2. SpringBoot中六批量更新Mysql 方式效率对比

    2023-12-07 17:34:05       12 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-07 17:34:05       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-07 17:34:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-07 17:34:05       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-07 17:34:05       20 阅读

热门阅读

  1. 【LVS实战】05 keepalived脑裂问题解决方案

    2023-12-07 17:34:05       28 阅读
  2. 再见了 shiro

    2023-12-07 17:34:05       36 阅读
  3. ARM Cortex-A、Cortex-M和Cortex-R简介

    2023-12-07 17:34:05       32 阅读
  4. 【ARM AMBA AXI 入门 18 - AXI4 NSAID 和 NS 详细介绍】

    2023-12-07 17:34:05       35 阅读
  5. [ffmpeg] find 编码器

    2023-12-07 17:34:05       38 阅读
  6. css3新增的伪类有哪些?

    2023-12-07 17:34:05       36 阅读
  7. 假设检验(三)(单侧假设检验)

    2023-12-07 17:34:05       34 阅读
  8. 远离危险的购买手机的渠道

    2023-12-07 17:34:05       33 阅读