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

2年前 (2022) 程序员胖胖胖虎阿
233 0 0

©Copyright 蕃薯耀 2022-06-25

https://www.cnblogs.com/fanshuyao/

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

this.updateById(entity);

this.update(entity, updateWrapper);

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

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);

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

UpdateWrapper<BizFile> updateWrapper = new UpdateWrapper<BizFile>();
updateWrapper.eq("id", bizFile.getId());
				
updateWrapper.set("parentId", parentId);
updateWrapper.set("path", newDirPath);

this.update(updateWrapper);

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

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

this.updateById(entity);

this.update(entity, updateWrapper);

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

©Copyright 蕃薯耀 2022-06-25

相关文章

暂无评论

暂无评论...