欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

MyBatisPlus通过ID更新数据为NULL的四种方法

2025年08月14日 Java
在使用 mybatis-plus 通过 id 更新数据时,若需将字段值设为null,可参考以下解决方案:方法一:使用@tablefield注解在实体类字段上添加注解,指定更新策略为忽略非空检查:pub

在使用 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<user> 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 等)。

到此这篇关于mybatisplus通过id更新数据为null的实现方法的文章就介绍到这了,更多相关mybatisplus更新为null内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!