新闻详情

新闻详情

首页 / 资讯中心 / 详情

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

发布时间:2026/11/12 4:14:00来源:尧图网络
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; }欢迎各位大佬留言。
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

【外设】之大彩串口显示屏 2026/11/11 13:52:51

【外设】之大彩串口显示屏

大彩串口屏初步使用 1 .官网下载 STM32 屏幕 GUI 设计资料 http://www.gz-dc.com/category/typeid/4112 找到 STM32 Keil 工程,移植相关代码因项目而异进行移植,由于项目简单,本人只对用到的指令接口进行修改。 比如:注意事项&…

阅读更多 →
无法下载Windows系统iso文件 2026/11/10 19:42:40

无法下载Windows系统iso文件

当我遇到这个问题的时候,我打开了一个网站: 登录 然后我打算下载的时候: 突然那个官方的连接就可以下载了:

阅读更多 →
【清华代码熊】DeepSeek V4.1 Flash 后训练详解 2026/11/11 9:31:44

【清华代码熊】DeepSeek V4.1 Flash 后训练详解

📌 上期解析了 DeepSeek V4.1 Flash 模型架构改进,本期解析 DeepSeek V4.1 Flash 预训练/后训练技术: 🌟 预训练:45T 文本 多模态混合语料、直接训练 sparse attention(取消 DeepSeek V4 的 dense 冷启动&…

阅读更多 →
Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ... 2026/11/11 5:36:08

Shuffle-R1: Efficient RL framework for Multimodal Large Language Models via Data-centric Dynamic ...

文章主要内容和创新点 主要内容 本文聚焦于多模态大语言模型(MLLM)强化学习(RL)训练中的效率问题,提出了一个名为Shuffle-R1的框架。研究发现,当前RL训练存在两个关键缺陷: 优势值坍缩(Advantage Collapsing):批次中大多数优势值集中在零附近,导致有效梯度信号被淹…

阅读更多 →
PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction 2026/11/11 15:37:39

PRvL: Quantifying the Capabilities and Risks of Large Language Models for PII Redaction

一、文章主要内容总结 本文聚焦于利用大型语言模型(LLMs)实现个人身份信息(PII)脱敏的研究,旨在解决传统脱敏方法(如基于规则的系统、领域特定命名实体识别(NER)模型)泛化能力差、跨格式/跨语境适应性弱的问题。 研究通过全面评估多种LLM架构(包括密集型LLM(D-LLM…

阅读更多 →
LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model 2026/11/10 17:14:10

LLaVA-RE: Binary Image-Text Relevancy Evaluation with Multimodal Large Language Model

文章主要内容和创新点 主要内容 本文聚焦于二进制图像-文本相关性评估任务(判断图像与文本“相关”或“不相关”),针对该任务中文本格式多样、相关性定义随场景变化等挑战,提出了基于多模态大语言模型(MLLM)的解决方案LLaVA-RE。 模型设计:LLaVA-RE基于LLaVA 1.5架构,…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉