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

1. 继承DefaultSqlInjector

java 复制代码
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 {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);

        // 添加一个替换方法
        methodList.add(new Replace());
        return methodList;
    }
}
java 复制代码
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 方法

java 复制代码
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;
    }

    @Override
    public 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. 实现一个批量替换的方法,作为调用入口

java 复制代码
    /**
     * 批量替换
     *
     * @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. 最终效果


相关推荐
sekaii16 分钟前
ReDistribution plan细节
linux·服务器·数据库
焱焱枫1 小时前
自适应SQL计划管理(Adaptive SQL Plan Management)在Oracle 12c中的应用
数据库·sql·oracle
2301_793069821 小时前
Spring Boot +SQL项目优化策略,GraphQL和SQL 区别,Spring JDBC 等原理辨析(万字长文+代码)
java·数据库·spring boot·sql·jdbc·orm
hhw1991121 小时前
spring boot知识点5
java·数据库·spring boot
ITPUB-微风2 小时前
功能开关聚合对象实践:提升金融领域的高可用性
网络·数据库·金融
去看日出2 小时前
Linux(centos)系统安装部署MySQL8.0数据库(GLIBC版本)
linux·数据库·centos
ONEPEICE-ing2 小时前
快速入门Springboot+vue——MybatisPlus多表查询及分页查询
前端·vue.js·spring boot·mybatis
Hanyaoo2 小时前
为什么mvcc中?m_ids 列表并不等同于 min_trx_id 和 max_trx_id 之间的所有事务 ID
数据库
偏右右3 小时前
PL/SQL 异常处理
数据库·sql·oracle
利瑞华3 小时前
Redis 存在线程安全问题吗?为什么?
数据库·redis·安全