Mybatis-Plus使用updateById()、update()将字段更新为null

本文主要介绍了Mybatis-Plus使用updateById()、update()将字段更新为null,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

一、问题背景

使用mybatis-plus时想将查询结果中某个字段值更新为null,由于之前存入了非null数据,如下一个duty_json字段,想做对象的更新操作(数据库设计允许为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);
    }

这种方式不影响其他方法,不需要修改全局配置,也不需要在字段上单独加注解,所以推荐使用该方式。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_47061482/article/details/132191205