MyBatis-Plus updateById 不更新null字段

一、问题描述

使用这两个方法,不会对实体中值为Null的属性(字段)进行更新。

1
2
3
this.updateById(entity);

this.update(entity, updateWrapper);

二、问题原因

原因:mybatis-plusfieldStrategy的策略有三种,分别是IGNORED-0-忽略,NOT_NULL-1-非NULL(默认策略),NOT_EMPTY-2-非空,所以造成不更新的原因是默认策略。

三、解决办法

  • 设置全局的 updateStrategy
1
2
3
4
5
6
mybatis-plus:
global-config:
dbConfig:
insertStrategy: NOT_NULL
updateStrategy: IGNORED
where-strategy: NOT_NULL
  • 对字段单独设置策略
1
@TableField(updateStrategy= FieldStrategy.IGNORED)
  • 使用mapperupdate
1
2
3
4
5
LambdaUpdateWrapper<xxx> wrapper = new LambdaUpdateWrapper<>();
wrapper.eq(xxx::getId, xxx.getId());
wrapper.set(xxx::getOrgUri, xxx.getOrgUri());
wrapper.set(xxx::getBeginTime, null);
xxxMapper.update(xxx, wrapper);
  • 使用LambdaUpdateWrapper(推荐)
1
2
3
4
5
6
7
8
9
10
11
LambdaUpdateWrapper<BizFile> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//过滤条件
lambdaUpdateWrapper.eq(BizFile::getId, bizFile.getId());

//下面为设置值
//由于parentId会为空,所以要使用LambdaUpdateWrapper
lambdaUpdateWrapper.set(BizFile::getParentId, parentId);
lambdaUpdateWrapper.set(BizFile::getPath, newDirPath);

//更新
this.update(lambdaUpdateWrapper);

1种就免了,第2、3种验证过都可以。


MyBatis-Plus updateById 不更新null字段
http://ysocket.pages.dev/2023/09/02/mybatis-plus-null-field-not-be-update/
作者
YSocket
发布于
202392
许可协议