Mybatis-Plus将字段更新为null不生效问题

出现的问题

问题是使用mybatis-plus中提供的updateById方法,想将查询结果中某个字段原本不为null的值更新为null(数据库设计允许为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 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;
 }

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Boy_Martin/article/details/126264676

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值