首页 > 其他分享 >Mybatis-Plus系列---【解决null值字段不更新的问题】

Mybatis-Plus系列---【解决null值字段不更新的问题】

时间:2022-12-10 13:02:03浏览次数:49  
标签:值字 更新 --- 修改 Plus 默认 Article null id

解决null值字段不更新的问题

1.问题

我的MP版本是3.3.2,用Mybatis-Plus的updateById()来更新数据时,无法将字段设置为null值(更新后数据还是原来的值)。

2.分析

默认情况下,Mybatis-Plus在更新时会判断字段是否为null,如果是null,则不设值(不将这个字段拼接为SQL的SET语句)。

3.推荐的解决方案

updateById默认是不修改值为null的字段

update默认是修改值为null的字段,优点:可以用Wrappers构造指定按什么修改的修改条件,但缺点是按id修改时也得手动指定。

saveOrUpdate中的Update默认是修改值为null的字段的,优势:参数直接就是实体类本身,默认的修改条件就是根据id修改,不用再指定修改条件为id。如果是存在就更新,不存在就新增的场景建议用这个,因为这个的更新自带更新null值的字段。

建议用下面这种方案,不建议用全局设置的,或者在某个字段上加"@TableField(strategy =FieldStrategy.IGNORED)"注解的方案。

public
boolean
updateArticleById(Integer id) {

​​Article article = Optional.ofNullable(articleMapper.selectById(id)).orElseThrow(RuntimeException::​​​​new​​​​);​​


​​ boolean i = ​​​​articleService.​​​​lambdaUpdate()​​


​​   .​​​​set(Article::getOfflineTime,​​​​null​​​​);​​


​​.set(Article::getContent,​​​​"try mybatis plus update null"​​​​);​​


​​.set(Article::getPublishTime,LocalDateTime.now().plusHours(​​​​8​​​​));​​


​​.eq(Article::getId,article.getId())​​

     .update();

​​return​​​ ​​i​​​​;​​

​​}​​

常见问题:

在使用Oracle数据库的时候,Mysql我没试,我遇到了一个问题:

Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. Cause: java.sql.SQLException: Invalid column type: 1111

解决方案:

在yml文件中配置

mybatis-plus:
configuration:
jdbc-type-for-null: 'null'

 

标签:值字,更新,---,修改,Plus,默认,Article,null,id
From: https://blog.51cto.com/u_15670038/5927494

相关文章