一、问题描述
MybatisPlus想将某个字段更新为null,直接set*(null)
,使用了updateById()
方法,但却没有生效。
二、问题原因
mybatis-plus的 FieldStrategy 有三种策略:
- IGNORED:0 忽略
- NOT_NULL:1 非 NULL,默认策略
- NOT_EMPTY:2 非空
而默认更新策略是NOT_NULL:非 NULL;即updateById()
方法更新数据时, 如果目标值为NULL值时则不进行更新。
三、解决方案
方法1 使用UpdateWrapper方式更新(推荐使用)
在mybatis-plus中,除了updateById方法,还提供了一个update方法,直接使用update方法也可以将字段设置为null,代码示例:
public int updateProduct(String productCode) {
UpdateWrapper<Product> wrapper = new UpdateWrapper<>();
wrapper.lambda().eq(Product::getProductCode, productCode)
.set(Product::getName, null);
return getBaseMapper().update(null, wrapper);
}
这种方式不影响其他方法,不需要修改全局配置,也不需要在字段上单独加注解,所以推荐使用该方式。
方法2 对某个字段设置单独的field-strategy
根据具体情况,在需要更新的字段中调整验证注解,如验证非空:
@TableField(strategy=FieldStrategy.NOT_EMPTY)
这样的话,我们只需要在需要更新为null的字段上,设置忽略策略,如下:
@TableField(strategy = FieldStrategy.IGNORED)
private String name;
在更新代码中,我们直接使用mybatis-plus中的updateById方法便可以更新成功,例如:
@Override
public boolean updateProductById(Integer id) {
Product product = getById(id);
product .setName(null);
updateById(product );
}
但这个方法也有局限性,当允许更新为null的字段多了,就需要各个字段都添加上该注解,显得有些麻烦。
方法3 设置全局的field-strategy (慎用)
properties文件格式:
mybatis-plus.global-config.db-config.field-strategy=ignored
yml文件格式:
mybatis-plus:
global-config:
#字段策略 0:"忽略判断",1:"非 NULL 判断",2:"非空判断"
field-strategy: 0
这样做是全局性配置,会对所有的字段都忽略判断。
但如果在执行updateById()
时, 有某些字段不想修改却没有传值,就会被更新为null,属于高危操作了。