默认的mybatic-plus执行updatebyid等操作时,如果相关字段内容是null值,不会自动进行更新的,这是个坑,需要注意。
问题原因
mybatis-plus fieldstrategy 有三种策略:
- ignored:0 忽略
- not_null:1 非 null,默认策略
- not_empty:2 非空
而默认更新策略是not_null
:非 null;即通过接口更新数据时数据为null值时将不更新进数据库。
解决方案
1. 设置全局的field-strategy
properties文件格式:
mybatis-plus.global-config.db-config.field-strategy=ignored
yml文件格式:
mybatis-plus: global-config: #字段策略 0:"忽略判断",1:"非 null 判断",2:"非空判断" field-strategy: 0
这样做是全局性配置,会对所有的字段都忽略判断,如果一些字段不想要修改,但是传值的时候没有传递过来,就会被更新为null,可能会影响其他业务数据的正确性。
2. 对某个字段设置单独的field-strategy
根据具体情况,在需要更新的字段中调整验证注解,如验证非空:
@tablefield(strategy=fieldstrategy.not_empty)
这样的话,我们只需要在需要更新为null的字段上,设置忽略策略,如下:
@tablefield(strategy = fieldstrategy.ignored) private string dutyjson;
在更新代码中,我们直接使用mybatis-plus中的updatebyid方法便可以更新成功,如下:
/** * updatebyid更新字段为null * @param id * @return */ @override public boolean updateproductbyid(integer id) { insuranceproduct insuranceproduct = optional.ofnullable(articlemapper.selectbyid(id)).orelsethrow(runtimeexception::new); insuranceproduct.setdutyjson(null); insuranceproductmapper.updatebyid(insuranceproduct); }
使用上述方法,如果需要这样处理的字段较多,那么就需要涉及对各个字段上都添加该注解,显得有些麻烦了。那么,可以考虑使用第三种方法,不需要在字段上加注解也能更新成功。
3. 使用updatewrapper方式更新(推荐使用)
在mybatis-plus中,除了updatebyid方法,还提供了一个update方法,直接使用update方法也可以将字段设置为null,代码如下:
/** * 根据商品唯一编码,更新商品责任的dutyjson */ public int updateproduct(string productcode) { insuranceproduct old = lambdaquery().eq(insuranceproduct::getproductcode, productcode).one(); updatewrapper<insuranceproduct> wrapper = new updatewrapper<>(); wrapper.lambda().eq(insuranceproduct::getproductcode, productcode) .set(insuranceproduct::getdutyjson, null) .eq(insuranceproduct::getdeleted, 0); return getbasemapper().update(old, wrapper); }
这种方式不影响其他方法,不需要修改全局配置,也不需要在字段上单独加注解,所以推荐使用该方式。
到此这篇关于mybatis-plus null值更新不生效问题解决的文章就介绍到这了,更多相关mybatis-plus null值更新不生效内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论