解决MyBatisPlus默认无法把字段更新成null的问题

2022-12-31 733点热度 0人点赞 0条评论

使用MyBatis-Plus遇到一个问题,就是使用updateById()、update()做更新的时候,我想要把字段更新成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:
  	#字段策略 ignored:"忽略判断",not_null:"非 NULL 判断",not_empty:"非空判断"
    field-strategy: ignored

这样做是全局性配置,会对所有的字段都忽略判断,如果一些字段不想要修改,但是传值的时候没有传递过来,就会被更新为null,可能会影响其他业务数据的正确性。

2. 对某个字段设置单独的field-strategy

根据具体情况,在需要更新的字段中调整验证注解,如验证非空:
@TableField(updateStrategy = FieldStrategy.NOT_EMPTY)

这样的话,我们只需要在需要更新为null的字段上,设置忽略策略,如下:

/**
 * 下架时间
 */
@TableField(updateStrategy = FieldStrategy.IGNORED)
private Date 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;
 }

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

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论