说到批量操作,我觉得思路也就是两种:一种是for循环一条一条更新,一种执行一条sql批量更新。
我们在这里说一下sql执行批量更新,直接上代码。
<!-- 通过入参list进行循环组装sql进行批量更新 -->
<update id="batchUpdate" parameterType="com.a.b.User">
<!-- 循环着组装sql语句
separator=";" 代表着每次循环完,在sql后面放一个分号
item="item" 循环List的每条的结果集
collection="list" list 即为传过来的参数User对象list -->
<foreach collection="list" separator=";" item="item">
update t_user set
user_name = #{item.name},
where id = #{item.id}
</foreach>
</update>
<!--case when更新-->
<update id="batchUpdate" parameterType="java.util.List">
update department
<trim prefix="set" suffixOverrides=",">
<trim prefix="sort =case" suffix="end,">
<foreach collection="list" item="item" index="index">
<if test="item.id !=null and item.id != -1">
when id=#{item.id} then #{item.sort}
</if>
</foreach>
</trim>
</trim>
where id in
<foreach collection="departments" index="index" item="item" separator="," open="(" close=")">
#{item.id}
</foreach>
</update>
下面这种方式,一般都会搭配唯一索引使用,如果存在就更新该记录,如果不存在insert新的记录
<!--ON DUPLICATE KEY UPDATE-->
<insert id="updateBatch" parameterType="java.util.List">
insert into t_user(id,name)VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.id,jdbcType=BIGINT},#{item.name,jdbcType=VARCHAR})
</foreach>
ON DUPLICATE KEY UPDATE
id=VALUES(id),name = VALUES(name)
</insert>