一、问题描述

更新字段为null 不更新问题.怎么解决?
只更新对象属性不为空的值,为null字段不更新。(默认就是这样)

//默认情况下null值不会被更新进去
this.updateById(entity);
//默认情况下null值不会被更新进去
this.update(entity, updateWrapper);

二、解决方案(null也更新进去)

1、使用LambdaUpdateWrapper(推荐)

LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
//过滤条件
lambdaUpdateWrapper.eq(User::getId, user.getId());
//下面为设置值          
//由于parentId会为空,所以要使用LambdaUpdateWrapper
lambdaUpdateWrapper.set(User::getParentId, parentId);
lambdaUpdateWrapper.set(User::getPath, newDirPath);
//更新
this.update(lambdaUpdateWrapper);

2、使用UpdateWrapper

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

UpdateWrapper<User> updateWrapper = new UpdateWrapper<User>();
updateWrapper.eq("id", user.getId());                
updateWrapper.set("parentId", parentId);
updateWrapper.set("path", newDirPath);
this.update(updateWrapper);

3、在实体中使用@TableField注解

在字段上加上注解:@TableField(updateStrategy = FieldStrategy.NOT_NULL)//字段非 null 时更新

public class YourEntity {
    @TableField(updateStrategy = FieldStrategy.NOT_NULL)//字段非 null 时更新
    private String fieldName;
    // 其他字段...
}

然后通过下面的方法更新

this.updateById(entity);
this.update(entity, updateWrapper);

策略说明:

  • FieldStrategy.IGNORED:无论字段是否为 null,始终更新(默认)。
  • FieldStrategy.NOT_NULL:字段非 null 时更新。
  • FieldStrategy.NOT_EMPTY:字段非 null 且非空字符串时更新(针对字符串)。
  • FieldStrategy.NEVER:不参与更新。

4、UpdateWrapper 加判断法

UpdateWrapper<UserEntity> wrapper = new UpdateWrapper<>();
wrapper.set(entity.getUserName() != null, "userName", entity.getUserName())
       .set(entity.getAge() != null,       "age"    , entity.getAge())
       .eq("id", entity.getId());

yourMapper.update(null, wrapper);

如果文章对你有一点点帮助,欢迎【点赞、留言、+ 关注】
您的关注是我持续创作的重要动力!有问题欢迎随时交流!多一个朋友多一条路!

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐