mybatisPlus更新字段值为null

问题描述

用Mybatis-Plus的update()或者updateById()来更新数据时,无法将字段设置为null值(更新后数据还是原来的值)。

TableField源码

FieldStrategy 源码

更新策略默认是不为Null

设置为null的方案

使用UpdateWrapper更新

userService.lambdaUpdate()
            .eq(User::getId, user.getId())
            .set(User::getUserName, user.getUserName())
            .set(User::getNickName, null)
            .update();

设置全局的field-strategy(不推荐)

mybatis-plus:
  global-config:
      # 字段策略 0:忽略判断,直接拼SQL, 1:非NULL, 2:非空,3:默认;4:永远不加入SQL
    field-strategy: 0

设置某个字段的field-strategy

在实体的某个字段上设置

@ApiModelProperty(value = "所在党组织")
    @TableField(updateStrategy = FieldStrategy.IGNORED)
    private Long partyOrgId;

更新时直接将值设置为null

staffInfo.setPartyOrgId(null)
经验分享 程序员 微信小程序 职场和发展