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 {

    @Override
    public 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;
    }

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

    /**
     * 批量替换
     *
     * @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

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus 提供了丰富的自定义 SQL 查询功能,可以满足复杂的查询需求。你可以使用 `@Select` 注解或者在 XML 文件中编写自定义 SQL 查询语句。 下面是使用注解方式编写自定义 SQL 查询的示例: ```java @Mapper public interface UserMapper extends BaseMapper<User> { @Select("SELECT * FROM user WHERE age > #{age}") List<User> selectUsersByAge(@Param("age") Integer age); } ``` 在上面的示例中,我们使用 `@Select` 注解来定义了一个自定义的查询方法 `selectUsersByAge`,查询年龄大于指定年龄的用户列表。 如果你更倾向于使用 XML 文件来编写自定义 SQL 查询语句,可以创建一个与 Mapper 接口对应的 XML 文件,并在该文件中定义自定义查询语句。 例如,假设你有一个 UserMapper 接口,对应的 XML 文件为 UserMapper.xml,你可以在 XML 文件中编写如下的自定义查询语句: ```xml <mapper namespace="com.example.mapper.UserMapper"> <select id="selectUsersByAge" resultType="com.example.entity.User"> SELECT * FROM user WHERE age > #{age} </select> </mapper> ``` 需要注意的是,自定义 SQL 查询语句中可以使用参数占位符(如 `#{age}`)来传递参数,也可以使用 MyBatis-Plus 提供的 `@Param` 注解来指定参数名称。 以上是自定义 SQL 查询的简单示例,实际使用时,你可以根据具体的业务需求编写更加复杂的查询语句,并灵活运用 MyBatis-Plus 提供的查询条件构造、动态 SQL 等功能来实现更精确的查询。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值