mybatis-plus添加replace(自定义)方法,添加sql注入器SqlInjector

本文主要是介绍mybatis-plus添加replace(自定义)方法,添加sql注入器SqlInjector,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 继承DefaultSqlInjector

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.springframework.stereotype.Component;import java.util.List;/*** 自定义sql注入器** @author yz* @since 2024/08/23*/
@Component
public class AntaiSqlInjector extends DefaultSqlInjector {@Overridepublic List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);// 添加一个替换方法methodList.add(new Replace());return methodList;}
}

import lombok.Getter;/*** 自定义MybatisPlus 支持 SQL 方法** @author yz* @since 2024/8/23 17:55*/
@Getter
public enum AntaiSqlMethod {REPLACE("replace", "替换一条数据", "<script>\nREPLACE INTO %s %s VALUES %s\n</script>");private final String method;private final String desc;private final String sql;AntaiSqlMethod(String method, String desc, String sql) {this.method = method;this.desc = desc;this.sql = sql;}}

2. 实现Replace 的 sql 方法

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlInjectionUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;/*** 替换一条数据(选择字段插入)存在则更新,不存在则插入** @author yz* @since 2024/08/23*/
@SuppressWarnings("all")
public class Replace extends AbstractMethod {/*** 自增主键字段是否忽略** @since 3.5.4*/private boolean ignoreAutoIncrementColumn;public Replace() {this(AntaiSqlMethod.REPLACE.getMethod());}/*** @param ignoreAutoIncrementColumn 是否忽略自增长主键字段* @since 3.5.4*/public Replace(boolean ignoreAutoIncrementColumn) {this(AntaiSqlMethod.REPLACE.getMethod());this.ignoreAutoIncrementColumn = ignoreAutoIncrementColumn;}/*** @param name 方法名* @since 3.5.0*/public Replace(String name) {super(name);}/*** @param name                      方法名* @param ignoreAutoIncrementColumn 是否忽略自增长主键字段* @since 3.5.4*/public Replace(String name, boolean ignoreAutoIncrementColumn) {super(name);this.ignoreAutoIncrementColumn = ignoreAutoIncrementColumn;}@Overridepublic MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {KeyGenerator keyGenerator = NoKeyGenerator.INSTANCE;SqlMethod sqlMethod = SqlMethod.INSERT_ONE;String columnScript = SqlScriptUtils.convertTrim(tableInfo.getAllInsertSqlColumnMaybeIf(null, ignoreAutoIncrementColumn),LEFT_BRACKET, RIGHT_BRACKET, null, COMMA);String valuesScript = LEFT_BRACKET + NEWLINE + SqlScriptUtils.convertTrim(tableInfo.getAllInsertSqlPropertyMaybeIf(null, ignoreAutoIncrementColumn),null, null, null, COMMA) + NEWLINE + RIGHT_BRACKET;String keyProperty = null;String keyColumn = null;// 表包含主键处理逻辑,如果不包含主键当普通字段处理if (StringUtils.isNotBlank(tableInfo.getKeyProperty())) {if (tableInfo.getIdType() == IdType.AUTO) {/* 自增主键 */keyGenerator = Jdbc3KeyGenerator.INSTANCE;keyProperty = tableInfo.getKeyProperty();// 去除转义符keyColumn = SqlInjectionUtils.removeEscapeCharacter(tableInfo.getKeyColumn());} else if (null != tableInfo.getKeySequence()) {keyGenerator = TableInfoHelper.genKeyGenerator(methodName, tableInfo, builderAssistant);keyProperty = tableInfo.getKeyProperty();keyColumn = tableInfo.getKeyColumn();}}String sql = String.format(AntaiSqlMethod.REPLACE.getSql(), tableInfo.getTableName(), columnScript, valuesScript);SqlSource sqlSource = super.createSqlSource(configuration, sql, modelClass);return this.addInsertMappedStatement(mapperClass, modelClass, methodName, sqlSource, keyGenerator, keyProperty, keyColumn);}
}

3. 实现一个批量替换的方法,作为调用入口

    /*** 批量替换** @param entityList 实体列表* @param batchSize  批量大小* @return {@link Boolean }*/default Boolean replaceBatch(Collection<T> entityList, int batchSize) {if (CollectionUtils.isEmpty(entityList)) {return false;}Class<T> entityClass = getEntityClass(entityList);Class<?> mapperClass = ClassUtils.toClassConfident(getTableInfo(entityClass).getCurrentNamespace());String sqlStatement = mapperClass.getName()+ StringPool.DOT+ AntaiSqlMethod.REPLACE.getMethod();return SqlHelper.executeBatch(entityClass, log, entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));}/*** 从集合中获取实体类型** @param entityList 实体集合* @param <T>        实体类型* @return 实体类型*/static <T> Class<T> getEntityClass(Collection<T> entityList) {Class<T> entityClass = null;for (T entity : entityList) {if (entity != null && entity.getClass() != null) {entityClass = (Class<T>) entity.getClass();break;}}Assert.notNull(entityClass, "error: can not get entityClass from entityList");return entityClass;}

4. 最终效果

image.png
image.png

这篇关于mybatis-plus添加replace(自定义)方法,添加sql注入器SqlInjector的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1110425

相关文章

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

SQL Server数据库死锁处理超详细攻略

《SQLServer数据库死锁处理超详细攻略》SQLServer作为主流数据库管理系统,在高并发场景下可能面临死锁问题,影响系统性能和稳定性,这篇文章主要给大家介绍了关于SQLServer数据库死... 目录一、引言二、查询 Sqlserver 中造成死锁的 SPID三、用内置函数查询执行信息1. sp_w

canal实现mysql数据同步的详细过程

《canal实现mysql数据同步的详细过程》:本文主要介绍canal实现mysql数据同步的详细过程,本文通过实例图文相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的... 目录1、canal下载2、mysql同步用户创建和授权3、canal admin安装和启动4、canal

Maven 配置中的 <mirror>绕过 HTTP 阻断机制的方法

《Maven配置中的<mirror>绕过HTTP阻断机制的方法》:本文主要介绍Maven配置中的<mirror>绕过HTTP阻断机制的方法,本文给大家分享问题原因及解决方案,感兴趣的朋友一... 目录一、问题场景:升级 Maven 后构建失败二、解决方案:通过 <mirror> 配置覆盖默认行为1. 配置示

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

使用jenv工具管理多个JDK版本的方法步骤

《使用jenv工具管理多个JDK版本的方法步骤》jenv是一个开源的Java环境管理工具,旨在帮助开发者在同一台机器上轻松管理和切换多个Java版本,:本文主要介绍使用jenv工具管理多个JD... 目录一、jenv到底是干啥的?二、jenv的核心功能(一)管理多个Java版本(二)支持插件扩展(三)环境隔

SQL中JOIN操作的条件使用总结与实践

《SQL中JOIN操作的条件使用总结与实践》在SQL查询中,JOIN操作是多表关联的核心工具,本文将从原理,场景和最佳实践三个方面总结JOIN条件的使用规则,希望可以帮助开发者精准控制查询逻辑... 目录一、ON与WHERE的本质区别二、场景化条件使用规则三、最佳实践建议1.优先使用ON条件2.WHERE用

MySQL存储过程之循环遍历查询的结果集详解

《MySQL存储过程之循环遍历查询的结果集详解》:本文主要介绍MySQL存储过程之循环遍历查询的结果集,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言1. 表结构2. 存储过程3. 关于存储过程的SQL补充总结前言近来碰到这样一个问题:在生产上导入的数据发现