MyBatis-Plus 字段为Null时不更新解决方案,MyBatis-Plus 更新空字段

时间:2025-02-20 16:21:43

©Copyright 蕃薯耀 2022-06-25

/fanshuyao/

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

(entity);

(entity, updateWrapper);

二、解决方案
1、使用LambdaUpdateWrapper (推荐)

LambdaUpdateWrapper<BizFile> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//过滤条件
(BizFile::getId, ());

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

//更新
(lambdaUpdateWrapper);

2、使用UpdateWrapper
和LambdaUpdateWrapper的区别,就是设置的字段写法不一样,下面是要使用数据库字段的,如果修改字段后,容易造成字段名称没有修改。

UpdateWrapper<BizFile> updateWrapper = new UpdateWrapper<BizFile>();
("id", ());
				
("parentId", parentId);
("path", newDirPath);

(updateWrapper);

3、在实体中使用@TableField注解
在字段上加上注解:@TableField(fill = )

@ApiModelProperty(“父ID”)
@TableField(fill = )
private Long parentId;
然后通过下面的方法更新

(entity);

(entity, updateWrapper);

================================

©Copyright 蕃薯耀 2022-06-25