Mybatis-Plus更新数据忽略null值问题
作者:isAcilles
本文主要介绍了Mybatis-Plus更新数据忽略null值问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
一、问题描述
近期正在家里美美休假,突然接个电话说是业务反馈生产上要操作置空某个字段,操作之后返回信息是成功,但实际没有反应。于是立刻打开电脑看看什么情况。
public Result<CstGrpInfoDto> edit(@Valid @RequestBody CstGrpInfoDto cstGrpInfoDto) { Result<CstGrpInfoDto> result = new Result<CstGrpInfoDto>(); CstGrpInfo cstGrpInfoEo = cstGrpInfoService.getById(cstGrpInfoDto.getId()); if (cstGrpInfoEo == null) { result.error400("未找到对应实体"); } else { BeanUtils.copyProperties(cstGrpInfoDto, cstGrpInfoEo); try { cstGrpInfoMapper.updateById(cstGrpInfoEo); result.success("修改成功!"); } catch (Exception e) { log.error(e.getMessage(), e); result.error400("修改失败!"); } } return result; }
大致逻辑就是这样,很简单的代码。
一开始想难道是BeanUtils的锅吗?于是DEBUG查看,发现EO的属性值都没有问题,问题只能是在mybatisPlus的updateById方法上。
通过调用查看日志,发现调用updateById方法拼接的SQL中,不包含属性值为null部分的字段.于是推测:mybatisPlus不会修改为null的字段,上网一搜果然是这样。
二、解决方案
方法1、使用UpdateWrapper方式更新
该方法适合明确需要修改的字段。
示例:
public int updateProduct(String productCode) { UpdateWrapper<Product> wrapper = new UpdateWrapper<>(); wrapper.lambda().eq(Product::getProductCode, productCode) .set(Product::getName, null); return getBaseMapper().update(null, wrapper); }
方法2、对某个字段设置单独的field-strategy
根据具体情况,在需要更新的字段中调整验证注解,如下
@TableField(strategy = FieldStrategy.IGNORED) private String name;
方法3、设置全局的field-strategy (慎用)
import com.baomidou.mybatisplus.core.config.GlobalConfig; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 添加分页插件 interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); return interceptor; } @Bean public GlobalConfig globalConfig() { GlobalConfig globalConfig = new GlobalConfig(); // 设置全局的更新策略 GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig(); dbConfig.setUpdateStrategy(FieldStrategy.IGNORED); // 设置为忽略 null 值 globalConfig.setDbConfig(dbConfig); return globalConfig; } }
properties文件格式:
mybatis-plus.global-config.db-config.update-strategy=ignored
yml文件格式:
mybatis-plus: global-config: db-config: update-strategy: ignored # 设置为忽略 null 值
使用建议:建议根据业务实际情况来选择使用哪种方式,对于有默认值和不可为null的数据,建议使用默认策略。
到此这篇关于Mybatis-Plus更新数据忽略null值问题的文章就介绍到这了,更多相关Mybatis-Plus更新数据忽略null值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!