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

 

问题背景

昨晚同事找我帮他看一个问题,他使用mybatis-plus中提供的updateById方法,想将查询结果中某个字段原本不为null的值更新为null(数据库设计允许为null),但结果该字段更新失败,执行更新方法后还是查询的结果。

 

问题原因

mybatis-plus FieldStrategy 有三种策略:

  • IGNORED:0 忽略
  • NOT_NULL:1 非 NULL,默认策略
  • NOT_EMPTY:2 非空

而默认更新策略是NOT_NULL:非 NULL;即通过接口更新数据时数据为NULL值时将不更新进数据库。

 

解决方案

针对上述问题,利用自己的项目环境(使用的mybatis-plus版本是3.1)测试了一下,总结了以下三种解决方案。

(以下解决方案是基于直接使用mybatis-plus提供的方法使用的,如果习惯写sql,当然你也可以直接在xml中写sql实现)

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 LocalDateTime offlineTime;

在更新代码中,我们直接使用mybatis-plus中的updateById方法便可以更新成功,如下:

 /**
* updateById更新字段为null
* @param id
* @return
*/
@Override
public boolean updateArticleById(Integer id) {
   Article article = Optional.ofNullable(articleMapper.selectById(id)).orElseThrow(RuntimeException::new);
   article.setContent("try mybatis plus update null again");
   article.setPublishTime(LocalDateTime.now().plusHours(8));
   article.setOfflineTime(null);
   int i = articleMapper.updateById(article);
   return i==1;
}

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

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

3. 使用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;
}

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

关于Mybatis-Plus使用updateById()、update()将字段更新为null的文章就介绍至此,更多相关Mybatis-Plus 字段更新为null内容请搜索编程宝库以前的文章,希望以后支持编程宝库

当我们在多个集群应用中使用到本地缓存时,在数据库数据得到更新后,为保持各个副本当前被修改的数据与数据库数据保持同步,在数据被操作后向其他集群应用发出被更新数据的通知,使其删除; ...