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


    ©Copyright 蕃薯耀 2022-06-25

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

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

    this.updateById(entity);
    
    this.update(entity, updateWrapper);
    
    • 1
    • 2
    • 3

    二、解决方案
    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

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

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

    this.updateById(entity);
    
    this.update(entity, updateWrapper);
    
    • 1
    • 2
    • 3

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

    ©Copyright 蕃薯耀 2022-06-25

  • 相关阅读:
    【剑指offer】二进制中1的个数&&2的幂
    【新日语2】单元复习(一)
    【题库】咸鱼之王答题挑战题库大全
    访问者模式简介
    C++ 求 最长连号
    java面试题整理《基础篇》八
    20240416,深拷贝&浅拷贝,对象初始化和清理,对象模型和THIS指针
    内网-win1
    C++完全背包
    【无标题】
  • 原文地址:https://blog.csdn.net/jjc4261/article/details/125528369