Mybatis-Plus更新數(shù)據(jù)忽略null值問題
一、問題描述
近期正在家里美美休假,突然接個電話說是業(yè)務反饋生產(chǎn)上要操作置空某個字段,操作之后返回信息是成功,但實際沒有反應。于是立刻打開電腦看看什么情況。
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查看,發(fā)現(xiàn)EO的屬性值都沒有問題,問題只能是在mybatisPlus的updateById方法上。
通過調(diào)用查看日志,發(fā)現(xiàn)調(diào)用updateById方法拼接的SQL中,不包含屬性值為null部分的字段.于是推測:mybatisPlus不會修改為null的字段,上網(wǎng)一搜果然是這樣。
二、解決方案
方法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、對某個字段設(shè)置單獨的field-strategy
根據(jù)具體情況,在需要更新的字段中調(diào)整驗證注解,如下
@TableField(strategy = FieldStrategy.IGNORED) private String name;
方法3、設(shè)置全局的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(); // 設(shè)置全局的更新策略 GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig(); dbConfig.setUpdateStrategy(FieldStrategy.IGNORED); // 設(shè)置為忽略 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 # 設(shè)置為忽略 null 值
使用建議:建議根據(jù)業(yè)務實際情況來選擇使用哪種方式,對于有默認值和不可為null的數(shù)據(jù),建議使用默認策略。
到此這篇關(guān)于Mybatis-Plus更新數(shù)據(jù)忽略null值問題的文章就介紹到這了,更多相關(guān)Mybatis-Plus更新數(shù)據(jù)忽略null值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Security OAuth2 實現(xiàn)登錄互踢的示例代碼
這篇文章主要介紹了Spring Security OAuth2實現(xiàn)登錄互踢的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-04-04Spring之SseEmitter實現(xiàn)讓你的進度條實時更新
Spring SseEmitter是一種實現(xiàn)服務器端推送事件(SSE)的機制,支持單向通信,適用于實時數(shù)據(jù)傳輸需求,通過代碼示例和應用場景分析,展示了如何在服務端和客戶端使用SseEmitter進行實時數(shù)據(jù)推送2025-02-02