MyBatisPlus通过ID更新数据为NULL的四种方法
作者:行星008
本文主要介绍了MyBatisPlus通过ID更新数据为NULL的实现方法,包括@TableField注解、UpdateWrapper、lambdaUpdate及全局配置,具有一定的参考价值,感兴趣的可以了解一下
在使用 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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!