首页/新闻资讯/正文详情

MybatisPlus扩展,按需求保存null字段,继承AbstractMethod

发布时间:2026/9/23 15:48:07 来源:云帆数科 栏目:资讯中心
MybatisPlus扩展,按需求保存null字段,继承AbstractMethod
mybatisPlus版本3.4.0本文主要是对MybatisPlus的更新方法进行扩展对set语句的非空校验进行自定义判断提供了两个方法模板/** * 根据主键更新字段null也会更新 * param entity * author zhangyong * date 2025/3/29 * return int */ int updateIgnoreNullById(Param(et) T entity); /** * 根据条件更新实体null也会更新 * author zhangyong * date 2025/3/29 * param entity: * param updateWrapper: * return int */ int updateIgnoreNull(Param(et) T entity, Param(ew) WrapperT updateWrapper);MybatisPlus扩展接口需要四个步骤第五步为使用1、定义方法扩展这部分必须实现injectMappedStatement接口接口的内容可以参考com.baomidou.mybatisplus.core.injector.methods包和com.baomidou.mybatisplus.extension.injector.methods.AlwaysUpdateSomeColumnById接口的写法。主要的拼接setsql的方法有两个,可以参考里面的实现来实现我们自己的逻辑没必要自己造轮子。a: AbstractMethod.filterTableFieldInfob.AbstractMethod.sqlSet其中调用的TableFieldInfo.convertIf接口非常重要是用来生成set字段外的if条件的可以按需求调整。如if testaccountId ! null ac.account_id #{accountId}, /if代码中需要注意return this.addUpdateMappedStatement(mapperClass, modelClass, updateIgnoreNull, sqlSource);的updateIgnoreNull需要和Mapper里的方法名一样重要a:根据自定义Wrapper条件更新数据,int updateIgnoreNullById(Param(et) T entity);package com.hk.abpms.data.api.config.method; import com.baomidou.mybatisplus.annotation.FieldStrategy; import com.baomidou.mybatisplus.core.enums.SqlMethod; import com.baomidou.mybatisplus.core.injector.AbstractMethod; import com.baomidou.mybatisplus.core.metadata.TableFieldInfo; import com.baomidou.mybatisplus.core.metadata.TableInfo; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; import java.util.function.Predicate; /** * 根据自定义Wrapper条件更新数据 * * author zhangyong * Date 2025/3/28 */ public class UpdateIgnoreNull extends AbstractMethod { private PredicateTableFieldInfo predicate; public UpdateIgnoreNull() { } Override public MappedStatement injectMappedStatement(Class? mapperClass, Class? modelClass, TableInfo tableInfo) { SqlMethod sqlMethod SqlMethod.UPDATE; if(tableInfo.getTableName().equals(cfg_api)){ System.out.println(tableInfo.getFieldList()); } String sqlSet this.filterTableFieldInfo(tableInfo.getFieldList(), this.getPredicate(), (i) - { //以下代码来自AbstractMethod.sqlSet String newPrefix et.; String sqlSet2 i.getColumn() ; if (StringUtils.isNotBlank(i.getUpdate())) { sqlSet2 sqlSet2 String.format(i.getUpdate(), i.getColumn()); } else { sqlSet2 sqlSet2 SqlScriptUtils.safeParam(newPrefix i.getEl()); } sqlSet2 sqlSet2 ,; return i.isWithUpdateFill() ? sqlSet2 : this.convertIf2(i,sqlSet2, this.convertIfProperty2(newPrefix, i.getProperty()), i.getUpdateStrategy()); }, \n); sqlSet SqlScriptUtils.convertSet(sqlSet); String sql String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlSet, this.sqlWhereEntityWrapper(true, tableInfo), this.sqlComment()); SqlSource sqlSource this.languageDriver.createSqlSource(this.configuration, sql, modelClass); return this.addUpdateMappedStatement(mapperClass, modelClass, updateIgnoreNull, sqlSource); } private String convertIf2(TableFieldInfo tableFieldInfo,final String sqlScript, final String property, final FieldStrategy fieldStrategy) { //判断Entity上的注解 if (fieldStrategy FieldStrategy.NEVER) { //字段标记为用不更新的 不需要set语句。TableField(updateStrategy FieldStrategy.NEVER) return null; } else if (!tableFieldInfo.isPrimitive() fieldStrategy ! FieldStrategy.IGNORED) { //如果字段没有FieldStrategy.IGNORED注解建议不要加这个注解加了注解所有涉及这个Entity的保存该字段为null都会更新 if(tableFieldInfo.isWithInsertFill()){ //判断Entity字段是否配置了 TableField(fill FieldFill.INSERT)注解理论上有这个注解的不需要修改比如createBy等字段所以此处set外拼接了if为空判断 return fieldStrategy FieldStrategy.NOT_EMPTY tableFieldInfo.isCharSequence() ? SqlScriptUtils.convertIf(sqlScript, String.format(%s ! null and %s ! , property, property), false) : SqlScriptUtils.convertIf(sqlScript, String.format(%s ! null, property), false); }else{ //不添加if为空判断null也会更新 return sqlScript; } } else { //不添加if为空判断null也会更新 return sqlScript; } } private String convertIfProperty2(String prefix, String property) { return StringUtils.isNotBlank(prefix) ? prefix.substring(0, prefix.length() - 1) [ property ] : property; } private PredicateTableFieldInfo getPredicate() { PredicateTableFieldInfo noLogic (t) - { return !t.isLogicDelete(); }; return this.predicate ! null ? noLogic.and(this.predicate) : noLogic; } }B:根据ID更新数据int updateIgnoreNull(Param(et) T entity, Param(ew) WrapperT updateWrapper);package com.hk.abpms.data.api.config.method; import com.baomidou.mybatisplus.annotation.FieldStrategy; import com.baomidou.mybatisplus.core.enums.SqlMethod; import com.baomidou.mybatisplus.core.injector.AbstractMethod; import com.baomidou.mybatisplus.core.metadata.TableFieldInfo; import com.baomidou.mybatisplus.core.metadata.TableInfo; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; import java.util.Objects; import java.util.function.Predicate; import java.util.stream.Collectors; /** * 根据ID更新数据 * * author zhangyong * Date 2025/3/28 */ public class UpdateIgnoreNullById extends AbstractMethod { public UpdateIgnoreNullById() { } Override public MappedStatement injectMappedStatement(Class? mapperClass, Class? modelClass, TableInfo tableInfo) { SqlMethod sqlMethod SqlMethod.UPDATE_BY_ID; if(tableInfo.getTableName().equals(cfg_api)){ System.out.println(tableInfo.getFieldList()); } String additional this.optlockVersion(tableInfo) tableInfo.getLogicDeleteSql(true, true); String sql String.format(sqlMethod.getSql(), tableInfo.getTableName(), this.sqlSet2(tableInfo.isWithLogicDelete(), false, tableInfo, false, et, et.), tableInfo.getKeyColumn(), et. tableInfo.getKeyProperty(), additional); SqlSource sqlSource this.languageDriver.createSqlSource(this.configuration, sql, modelClass); return this.addUpdateMappedStatement(mapperClass, modelClass, updateIgnoreNullById, sqlSource); } public String getAllSqlSet2( TableInfo table,boolean ignoreLogicDelFiled, final String prefix) { String newPrefix prefix null ? : prefix; return (String)table.getFieldList().stream().filter((i) - { if (!ignoreLogicDelFiled) { return true; } else { return !table.isWithLogicDelete() || !i.isLogicDelete(); } }).map((i) - { String sqlSet2 i.getColumn() ; if (StringUtils.isNotBlank(i.getUpdate())) { sqlSet2 sqlSet2 String.format(i.getUpdate(), i.getColumn()); } else { sqlSet2 sqlSet2 SqlScriptUtils.safeParam(newPrefix i.getEl()); } sqlSet2 sqlSet2 ,; return i.isWithUpdateFill() ? sqlSet2 : this.convertIf2(i,sqlSet2, this.convertIfProperty2(newPrefix, i.getProperty()), i.getUpdateStrategy()); }).filter(Objects::nonNull).collect(Collectors.joining(\n)); } protected String sqlSet2(boolean logic, boolean ew, TableInfo table, boolean judgeAliasNull, final String alias, final String prefix) { String sqlScript this.getAllSqlSet2(table,logic, prefix); if (judgeAliasNull) { sqlScript SqlScriptUtils.convertIf(sqlScript, String.format(%s ! null, alias), true); } if (ew) { sqlScript sqlScript \n; sqlScript sqlScript SqlScriptUtils.convertIf(SqlScriptUtils.unSafeParam(ew.sqlSet), String.format(%s ! null and %s ! null, ew, ew.sqlSet), false); } sqlScript SqlScriptUtils.convertSet(sqlScript); return sqlScript; } private String convertIf2(TableFieldInfo tableFieldInfo,final String sqlScript, final String property, final FieldStrategy fieldStrategy) { if (fieldStrategy FieldStrategy.NEVER) { return null; } else if (!tableFieldInfo.isPrimitive() fieldStrategy ! FieldStrategy.IGNORED) { if(tableFieldInfo.isWithInsertFill()){ return fieldStrategy FieldStrategy.NOT_EMPTY tableFieldInfo.isCharSequence() ? SqlScriptUtils.convertIf(sqlScript, String.format(%s ! null and %s ! , property, property), false) : SqlScriptUtils.convertIf(sqlScript, String.format(%s ! null, property), false); }else{ return sqlScript; } } else { return sqlScript; } } private String convertIfProperty2(String prefix, String property) { return StringUtils.isNotBlank(prefix) ? prefix.substring(0, prefix.length() - 1) [ property ] : property; } }2、将方法加入MybatisPlus进行管理package com.hk.abpms.data.api.config; import com.baomidou.mybatisplus.core.injector.AbstractMethod; import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector; import com.baomidou.mybatisplus.extension.injector.methods.AlwaysUpdateSomeColumnById; import com.hk.abpms.data.api.config.method.UpdateIgnoreNull; import com.hk.abpms.data.api.config.method.UpdateIgnoreNullById; import java.util.List; /** * sql方法注入 * * author zhangyong * Date 2025/3/27 */ public class MybatisSqlInjector extends DefaultSqlInjector { Override public ListAbstractMethod getMethodList(Class? mapperClass) { ListAbstractMethod methodList super.getMethodList(mapperClass); // 添加自定义的更新方法AlwaysUpdateSomeColumnById 会更新所有字段包括空字段 methodList.add(new UpdateIgnoreNullById()); methodList.add(new UpdateIgnoreNull()); return methodList; } }3、将Injector加入springBean管理package com.hk.abpms.data.api.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * MybatisPlus的额外配置类 * * author zhangyong * Date 2025/3/28 */ Configuration public class MyBatisPlusConfig { Bean public MybatisSqlInjector customSqlInjector() { return new MybatisSqlInjector(); } }4、在BaseMapper中定义与第一步同名的方法注意参数Param(et)名字要和第一步的名称对应package com.hk.abpms.data.api.config; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; /** * 基础mapper * * author zhangyong * Date 2025/3/28 */ public interface BaseCommonMapperT extends BaseMapperT { /** * 根据主键更新字段null也会更新 * param entity * author zhangyong * date 2025/3/29 * return int */ int updateIgnoreNullById(Param(et) T entity); /** * 根据条件更新实体null也会更新 * author zhangyong * date 2025/3/29 * param entity: * param updateWrapper: * return int */ int updateIgnoreNull(Param(et) T entity, Param(ew) WrapperT updateWrapper); }5、业务Mapper继承公共的BaseCommonMapper后就可正常使用里面的方法最后如果自己new了SqlSessionFactory需要将MybatisSqlInjector手动设置进去Bean ConditionalOnMissingBean(SqlSessionFactory.class) public SqlSessionFactory sqlSessionFactory(DataSource dataSource, MybatisPlusInterceptor interceptor, GlobalConfig globalConfig) throws Exception { MybatisSqlSessionFactoryBean bean new MybatisSqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setPlugins(interceptor); bean.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(classpath*:mapping/**/*.xml)); bean.setGlobalConfig(globalConfig); return bean.getObject(); } /** * GlobalConfig必须设置自定义SqlInjector否则BaseCommonMapper的自定义方法updateNullFieldById/updateNullField * 不会被注入调用时抛BindingException: Invalid bound statement (not found) */ Bean public GlobalConfig globalConfig(MybatisSqlInjector mybatisSqlInjector) { GlobalConfig config new GlobalConfig(); config.setSqlInjector(mybatisSqlInjector); config.setMetaObjectHandler(new DefaultDBFieldHandler()); return config; }欢迎各位大佬留言。

相关推荐

毕设攻坚全攻略:用好 AI 学术助手,高效搞定毕业论文
毕设攻坚全攻略:用好 AI 学术助手,高效搞定毕业论文

每一年毕业季,无数应届生都要踏上毕业设计这条漫长赛道。从敲定选题、翻阅海量文献,到撰写正文、绘制图表,再到格式调整、论文自查、准备答辩,一环扣一环,任何一个环节卡住,都会拖慢整体进度。繁重的事务性… · 2026/9/23 15:48:07

Apache TVM RPC 模块完全指南:远程设备连接、模块上传与资源调度
Apache TVM RPC 模块完全指南:远程设备连接、模块上传与资源调度

Apache TVM RPC 模块完全指南:远程设备连接、模块上传与资源调度 【免费下载链接】tvm Open deep learning compiler stack for cpu, gpu and specialized accelerators 项目地址: https://gitcode.com/gh_mirrors/tvm7/tvm tvm.rpc 是 Apache TVM 官方的轻量… · 2026/9/23 15:48:01

Ceph crushtool 实战完全指南:CRUSH map 的编译、构建、测试与调优
Ceph crushtool 实战完全指南:CRUSH map 的编译、构建、测试与调优

存储分布式文件系统对象存储后端高可用 【免费下载链接】ceph Ceph is a distributed object, block, and file storage platform 项目地址: https://gitcode.com/gh_mirrors/ce/ceph 点击查看 免费下载 crushtool 是 Ceph 中专门用于创建、编译、反编译与测试 CR… · 2026/9/23 15:48:01

基于LSTM的SDN流量预测与主动调度系统设计与实现
基于LSTM的SDN流量预测与主动调度系统设计与实现

简介:基于SDN的流量预测与调度系统是一套完整可运行的Python工程源码,配套详细项目说明,适合计算机相关专业学生用于毕业设计、课程设计或工程实践,也适合企业技术人员快速搭建与二次开发。系统内置用户、部门、角色、权限、菜单、… · 2026/9/23 17:08:40

AI 论文工具在文献综述写作中的应用|paperxie 实操指南
AI 论文工具在文献综述写作中的应用|paperxie 实操指南

文献综述是毕业论文的核心组成部分,也是很多应届生的一大难点。一篇合格的文献综述,不是简单罗列文献摘要,而是梳理领域发展脉络,归纳现有成果,找到研究缺口,为本论文的研究方向提供支撑。大量学生在撰写文… · 2026/9/23 17:08:40

AI 论文工具如何提升毕设效率|paperxie 全流程效率优化方法
AI 论文工具如何提升毕设效率|paperxie 全流程效率优化方法

对于正在准备毕业论文的应届生而言,毕设最大的痛点往往不是科研本身,而是大量低价值、重复性的事务性工作。文献检索整理、格式调整、图表绘制、文稿修改、PPT 制作,这些工作会占用大量时间,挤压课题研究、数据分析的精力。选对 A… · 2026/9/23 17:08:40

5个KL性能优化死穴:学会语法却搭不起项目
5个KL性能优化死穴:学会语法却搭不起项目

5个KL性能优化死穴:学会语法却搭不起项目 刚写完Hello World,转头想搭个高并发服务,代码一跑CPU直接飙满?这不仅是KL的坑,更是无数人从语法跨入实战时的第一道坎。很多人以为KL只是换个语法糖,其实它的 性能优化… · 2026/9/23 17:08:39

Robot Framework 时间格式完全指南:数字、时间字符串与计时器字符串详解
Robot Framework 时间格式完全指南:数字、时间字符串与计时器字符串详解

Robot Framework 时间格式完全指南:数字、时间字符串与计时器字符串详解 【免费下载链接】robotframework Generic automation framework for acceptance testing and RPA 项目地址: https://gitcode.com/gh_mirrors/ro/robotframework Robot Framework 拥有… · 2026/9/23 17:08:33

搞定 macd计算公式 的 5 个最佳实践
搞定 macd计算公式 的 5 个最佳实践

搞定 macd计算公式 的 5 个最佳实践 刚把量化交易系统从 Python 2 升级到 3,或者从旧版 Pandas 换到新版,是不是发现以前好用的 macd计算公式 直接报错了?版本升级后 API… · 2026/9/23 17:08:33

3招搞定手机怎么下载微信面试难题实战项目解析
3招搞定手机怎么下载微信面试难题实战项目解析

3招搞定手机怎么下载微信面试难题实战项目解析 面试被问“手机怎么下载微信”背后的原理,90%的人答不上来。别笑,这看似弱智的问题,实则是考察你对移动应用分发机制、安全校验及网络协议理解的试金石。我带过不少校招新人,他们背了八股文,却连一个A… · 2026/9/23 0:00:03

你有新短消息请注意查收:3个新手避坑指南搞定消息系统选型
你有新短消息请注意查收:3个新手避坑指南搞定消息系统选型

你有新短消息请注意查收:3个新手避坑指南搞定消息系统选型 面试被问“高并发下如何保证消息不丢失”,你张口就是“用Redis”,结果面试官追问“如果Redis宕机了怎么办”,你瞬间卡壳。这种场景太常见了,很多新手在背八股文时,只记住了技术名词… · 2026/9/23 0:00:29

Win7无线热点配置工具源码解析:解决API失效的3个实战技巧
Win7无线热点配置工具源码解析:解决API失效的3个实战技巧

Win7无线热点配置工具源码解析:解决API失效的3个实战技巧 Win7无线热点配置工具在Win10/11上跑不动?不是你的问题,是版本升级后 API 全变了。很多老项目里的 netsh wlan… · 2026/9/23 0:00:36

了解更多?预约专属演示

我们的顾问将为您一对一讲解产品与方案

企业微信二维码