项目场景:
MYSQL批量更新操作,单个更新不受影响
问题描述
咋一看下面的sql是没有问题的,我之前也是这么认为的,但是实际是会产生bug,会将数据库的值给覆写成null。找了很久还是查binlog查询问题了。
批量更新时当有条件判断是否需要更新该字段,且批量数据中,有部分数据的条件不通过,此时按预期效果是不生成针对该数据的更新语句,但是结果是系统会自动生成更新成Null的语句,导致数据被覆盖,远离了设计的初衷。
update temp
<trim prefix="set" suffixOverrides=",">
<trim prefix="name= case" suffix="end,">
<foreach collection="list" index="index" item="item">
<if test="null !=item.name and '' != item.name ">
when id = #{item.id,jdbcType=INTEGER} then
#{item.name,jdbcType=VARCHAR}
</if>
</foreach>
</trim>
</trim>
where id in
<foreach close=")" collection="list" item="item" open="(" separator=", ">
#{item.id,jdbcType=INTEGER}
</foreach>
解决方案:
批量更新时更新字段如不满足条件则更新为原数据值即可,避免系统自动生成更新成null。
update temp
<trim prefix="set" suffixOverrides=",">
<trim prefix="name= case" suffix="end,">
<foreach collection="list" index="index" item="item">
when id = #{item.id,jdbcType=INTEGER} then
<choose>
<when test="null !=item.name and '' != item.name ">
#{item.name,jdbcType=VARCHAR}
</when>
<otherwise>
name
</otherwise>
</choose>
</foreach>
</trim>
</trim>
where id in
<foreach close=")" collection="list" item="item" open="(" separator=", ">
#{item.id,jdbcType=INTEGER}
</foreach>