首页

解决baomidou的mybatis-plus中提供的updateById方法空NULL无法正常更新问题

标签:updateById,baomidou,mybatis-plus     发布时间:2022-08-17   

一、前言

基于baomidoumybatis-plus中提供的updateById方法,无法实现对NULL空值对象字段进行更新,就是结果该字段更新失败,执行更新方法后数据库字段值没有变 - 想将查询结果中某个字段原本不为null的值更新为null(数据库设计允许为null)。

articleMapper.update(Wrappers.<Article >lambdaUpdate()@b@        .set(Article ::getContent, article.getContent())@b@        .eq(Article ::getId, article.getId()));

二、解决方法

使用UpdateWrapper方式更新 -  在mybatis-plus中,除了updateById方法,还提供了一个update方法,直接使用update方法也可以将字段设置为null,代码如下

/**@b@  * update更新字段为null@b@  * @param id@b@  * @return@b@  */@b@ @Override@b@ public boolean updateArticleById(Integer id) {@b@     Article article = Optional.ofNullable(articleMapper.selectById(id)).orElseThrow(RuntimeException::new);@b@     LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();@b@     updateWrapper.set(Article::getOfflineTime,null);@b@     updateWrapper.set(Article::getContent,"try mybatis plus update null");@b@     updateWrapper.set(Article::getPublishTime,LocalDateTime.now().plusHours(8));@b@     updateWrapper.eq(Article::getId,article.getId());@b@     int i = articleMapper.update(article, updateWrapper);@b@     return i==1;@b@ }