本文主要是介绍【转载】Mybatis-Plus使用updateById()、update()将字段更新为null,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题背景
昨晚同事找我帮他看一个问题,他使用mybatis-plus中提供的updateById方法,想将查询结果中某个字段原本不为null的值更新为null(数据库设计允许为null),但结果该字段更新失败,执行更新方法后还是查询的结果。
问题原因
mybatis-plus FieldStrategy 有三种策略:
- IGNORED:0 忽略
- NOT_NULL:1 非 NULL,默认策略
- NOT_EMPTY:2 非空
而默认更新策略是NOT_NULL:非 NULL;即通过接口更新数据时数据为NULL值时将不更新进数据库。
解决方案
针对上述问题,利用自己的项目环境(使用的mybatis-plus版本是3.1)测试了一下,总结了以下三种解决方案。
(以下解决方案是基于直接使用mybatis-plus提供的方法使用的,如果习惯写sql,当然你也可以直接在xml中写sql实现)
1. 设置全局的field-strategy
在配置文件中,我们可以修改策略,如下:
#properties文件格式:
mybatis-plus.global-config.db-config.field-strategy=ignored#yml文件格式:
mybatis-plus:global-config:#字段策略 0:"忽略判断",1:"非 NULL 判断",2:"非空判断"field-strategy: 0
这样做是全局性配置,会对所有的字段都忽略判断,如果一些字段不想要修改,但是传值的时候没有传递过来,就会被更新为null,可能会影响其他业务数据的正确性。
2. 对某个字段设置单独的field-strategy
根据具体情况,在需要更新的字段中调整验证注解,如验证非空:
@TableField(strategy=FieldStrategy.NOT_EMPTY)
这样的话,我们只需要在需要更新为null的字段上,设置忽略策略,如下:
/*** 下架时间*/
@TableField(strategy = FieldStrategy.IGNORED)
private LocalDateTime offlineTime;
在更新代码中,我们直接使用mybatis-plus中的updateById方法便可以更新成功,如下:
/*** updateById更新字段为null* @param id* @return*/@Overridepublic boolean updateArticleById(Integer id) {Article article = Optional.ofNullable(articleMapper.selectById(id)).orElseThrow(RuntimeException::new);article.setContent("try mybatis plus update null again");article.setPublishTime(LocalDateTime.now().plusHours(8));article.setOfflineTime(null);int i = articleMapper.updateById(article);return i==1;}
使用上述方法,如果需要这样处理的字段较多,那么就需要涉及对各个字段上都添加该注解,显得有些麻烦了。
那么,可以考虑使用第三种方法,不需要在字段上加注解也能更新成功。
3. 使用UpdateWrapper方式更新
在mybatis-plus中,除了updateById方法,还提供了一个update方法,直接使用update方法也可以将字段设置为null,代码如下:
/*** update更新字段为null* @param id* @return*/@Overridepublic boolean updateArticleById(Integer id) {Article article = Optional.ofNullable(articleMapper.selectById(id)).orElseThrow(RuntimeException::new);LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();updateWrapper.set(Article::getOfflineTime,null);updateWrapper.set(Article::getContent,"try mybatis plus update null");updateWrapper.set(Article::getPublishTime,LocalDateTime.now().plusHours(8));updateWrapper.eq(Article::getId,article.getId());int i = articleMapper.update(article, updateWrapper);return i==1;}
这种方式不影响其他方法,不需要修改全局配置,也不需要在字段上单独加注解,所以推荐使用该方式。
这篇关于【转载】Mybatis-Plus使用updateById()、update()将字段更新为null的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!