MyBatis-Plus 通过 ID 更新数据为NULL总结

在使用 MyBatis-Plus 通过 ID 更新数据时,若需将字段值设为 null,可参考以下解决方案:

方法一:使用 @TableField 注解

在实体类字段上添加注解,指定更新策略为忽略非空检查:

public class User {
    @TableField(strategy = FieldStrategy.IGNORED)
    private String email;
}

调用 updateById 时,该字段即使为 null 也会被更新。

方法二:使用 UpdateWrapper 手动设置

通过 UpdateWrapper 显式指定需更新的字段:

User user = new User();
user.setId(1L);

UpdateWrapper updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id", user.getId())
             .set("email", null); // 显式设置 null

userMapper.update(null, updateWrapper);

此方法灵活控制需要更新的字段。

方法三:全局配置(谨慎使用)

在配置类中设置全局更新策略为忽略非空检查:

@Configuration
public class MybatisPlusConfig {
    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig config = new GlobalConfig();
        config.setDbConfig(new GlobalConfig.DbConfig()
                .setUpdateStrategy(FieldStrategy.IGNORED));
        return config;
    }
}

注意:此配置会影响所有更新操作,需确保数据库约束允许字段为 null

方法四:使用 lambdaUpdate

通过 Lambda 表达式构建更新条件:

User user = new User();
user.setId(1L);

userMapper.lambdaUpdate()
          .eq(User::getId, user.getId())
          .set(User::getEmail, null)
          .update();

简洁且类型安全。

总结

  • 个别字段处理:使用 @TableField 注解。
  • 灵活单次更新:选择 UpdateWrapper 或 lambdaUpdate
  • 全局处理(谨慎):配置全局策略。

注意事项

  • 确保数据库字段允许 NULL,否则会引发异常。
  • 全局配置需全面测试,避免意外覆盖非空字段。
  • 根据 MyBatis-Plus 版本调整策略名称(如 FieldStrategy 在 3.x 后更名为 FieldFill 等)。

        这篇博客到这里就接近尾声了,希望我的分享能给您带来一些启发和帮助,别忘了点赞、收藏。您的每一次互动、鼓励是我持续创作的动力!期待与您再次相遇,共同探索更广阔的世界!

你可能感兴趣的:(Mybatis,框架,java,开发语言,spring,boot,mybatis,后端)