使用Mybatis-plus在进行字段更新操作设置字段值为null,使用如下的操作语句:
LambdaUpdateWrapper<Entity> wrapper = new LambdaUpdateWrapper<>();
wrapper.set(Entity::getField,null);
wrapper.eq(Entity::getId,1);
this.update(wrapper)
发现打印出来的sql只有更新条件,没有field=null,导致更新报错。
这是为什么呢?这是因为Mybatis-plus在更新的时候做了null判断,默认不更新为null的传参字段,但业务如此,我们应该怎么写呢?
方法一:调整全局的验证策略
注入配置 GlobalConfiguration 属性 fieldStrategy
方法二:调整字段验证注解
根据具体情况,在需要更新的字段中调整验证注解,如验证非空:
@TableField(strategy=FieldStrategy.NOT_EMPTY)
方法三:使用 UpdateWrapper
使用以下方法来进行更新操作:
例1.
this.mapper.update(null,
Wrappers.<Entity>lambdaUpdate()
.set(Entity::getField, null)
.eq(Entity::getId, id));
例2.
UpdateWrapper<Entity> updateWrapper = new UpdateWrapper<>();
updateWrapper.set("field", null);
updateWrapper.eq("id", 2)
this.update(updateWrapper);
这样我们就很容易的处理了使用Mybatis-plus设置字段为空不生效的问题了。