ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

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

2026/9/10 17:29:41 拓冰建站 浏览量
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>endwhere 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>