mysql begin end 批量更新_MySql使用case when then end where 关键字执行批量更新(batchUpdate)时的避坑指南...

博客讲述了在使用Mybatis-Plus进行批量更新时遇到的两个问题:1) 必须提供WHERE条件以防止全表更新;2) Excel数据源中空值可能导致其他行数据被覆盖。为解决这些问题,作者采取了先查询数据库、再做非空检查的策略,确保更新的准确性。上线后,生产环境中未出现数据问题。
摘要由CSDN通过智能技术生成

前一段做一个批量更新的需求,数据的来源是一个Excel文件,列有值的话,就更新,没值的话,就忽略。

首先可以使用mybatis-plus的com.baomidou.mybatisplus.extension.service包下的IService接口里面的批量方法

但它的实现原理是伪批量,所以我参照系统中之前的批量更新写法,写了一个Mysql自带的批量更新,Map.xml中的代码如下:

UPDATE product_online

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.productName,jdbcType=VARCHAR}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.productSpecific,jdbcType=VARCHAR}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.productUnit,jdbcType=VARCHAR}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.weight,jdbcType=DECIMAL}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.originPlace,jdbcType=VARCHAR}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.shelfLife,jdbcType=VARCHAR}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.productBrief,jdbcType=VARCHAR}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.storageType,jdbcType=VARCHAR}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.isReturn,jdbcType=TINYINT}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.subTitle,jdbcType=VARCHAR}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.keywords,jdbcType=VARCHAR}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.updatedTime}

when product_code = #{item.productCode,jdbcType=VARCHAR} then #{item.updatedBy,jdbcType=VARCHAR}

product_code = #{item.productCode,jdbcType=VARCHAR}

但这种方式有两个大坑!!

1号坑:使用 case when then end语句 批量更新时,where条件是必须的,不然默认会更新所有的,把原值覆盖成数据库类型的默认值!!

2号坑:我的数据来源是一个Excel文件,比如说Excel文件中共100行数据,其中只要有一行数据 在第3列有值,那么批量更新的时候,这100行数据的第3列都必须得有值,不然的话,数据库会把其他第3列的值覆盖成数据库类型的默认值!!

鉴于这两个坑的存在,我在批量更新前,就必须得先去数据库中查,得到查询结果的List,然后对每个列进行非空检验,如果为空,就把数据库中的值赋给该列,这样就可以避免 误操作篡改数据了。

这个功能上线后,我心里还是很忐忑的,必经update操作一定要谨慎,但最近观察一段时间的使用后,生产上没出现数据问题,哈哈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值