mybatis-plus 的默认配置 在调用 baseMapper.updateById 时 ,如果实体类中的字段属性为null,那么不将该属性更新到数据库。

mybatis-plus FieldStrategy 有三种策略:

IGNORED:0 忽略
NOT_NULL:1 非 NULL,默认策略
NOT_EMPTY:2 非空
而默认更新策略是NOT_NULL:非 NULL;即通过接口更新数据时数据为NULL值时将不更新进数据库。

如果想将查询结果中某个字段原本不为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 Date buyTime;

使用上述方法,如果需要这样处理的字段较多,那么就需要涉及对各个字段上都添加该注解,显得有些麻烦了。

那么,可以考虑使用第三种方法,不需要在字段上加注解也能更新成功。

  1. 使用UpdateWrapper方式更新

在mybatis-plus中,除了updateById方法,还提供了一个update方法,直接使用update方法也可以将字段设置为null,代码如下:

 /**
  * update更新字段为null
  * @param id
  * @return
  */
 @Override
 public boolean updateArticleById(Integer id) {
     Article article = Optional.ofNullable(articleMapper.selectById(id)).orElseThrow(RuntimeException::new);
     LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
     updateWrapper.set(Article::getOfflineTime,null);
     updateWrapper.set(Article::getContent,"try mybatis plus update null");
     updateWrapper.set(Article::getPublishTime,LocalDateTime.now().plusHours(8));
     updateWrapper.eq(Article::getId,article.getId());
     int i = articleMapper.update(article, updateWrapper);
     return i==1;
 }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐