MyBatis Interceptor修改SQL

背景:需要分表的情况下 不借助中间件 如何实现管理后台页面的多表聚合查询?

想法是通过mybatis 提供的拦截器 重写sql


package com.jdh.general.config;

import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.jdh.general.common.annotation.CallWhen;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 单库分表 做聚合查询 拦截器
 *
 * @author hubin
 * @since 2016-08-16
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
@Intercepts({@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class SimpleUnionQuery extends AbstractSqlParserHandler implements Interceptor {


    @SuppressWarnings("unused")
    private static final Log logger = LogFactory.getLog(SimpleUnionQuery .class);

    private Properties properties;


    final static String _FROM = " FROM ";
    final static String _WHERE = " WHERE ";
    final static String _LIMIT = " LIMIT ";

    /**
     * intercept 方法用来对拦截的sql进行具体的操作
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Method method = invocation.getMethod();
        //由自定义注解配置
        CallWhen annotation = method.getAnnotation(CallWhen.class);
        ArrayList tableNums = new ArrayList<>();
        tableNums.add("_1");
        tableNums.add("_2");


        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        String origSql = boundSql.getSql();

        //多少个union all 表构建多少次参数
        List tempParam = boundSql.getParameterMappings();
        tableNums.forEach(tableNum->{
            boundSql.getParameterMappings().addAll(tempParam);
        });

        // 组装新的 sql
        String newSql = sqlUpdate(origSql,tableNums);

        // 重新new一个查询语句对象
        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
                boundSql.getParameterMappings(), boundSql.getParameterObject());

     // 把新的查询放到statement里
        MappedStatement newMs = newMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }

        Object[] queryArgs = invocation.getArgs();
        queryArgs[0] = newMs;


        return invocation.proceed();
    }

    /**
     *
     * @param sql 源sql
     * @param tableNums 需要构建表名个数
     * @return
     */
    public String sqlUpdate(String sql, ArrayList tableNums) {

        String[] froms = sql.split(_FROM);
        String column = froms[0];
        String fromAfter = froms[1];

        String[] wheres = fromAfter.split(_WHERE);

        String table = wheres[0];
        String whereAfter = wheres[1];

        String[] limits = whereAfter.split(_LIMIT);

        String condition = limits[0];
        String limit = limits[1];

        StringBuilder sqlContent = new StringBuilder();
        for (int i = 0; i < tableNums.size(); i++) {
            sqlContent.append(column)
                    .append(_FROM)
                    .append(table.trim() + tableNums.get(i))
                    .append(_WHERE)
                    .append(condition);
            if ((i + 1) < tableNums.size()) sqlContent.append(" UNION All \n");
        }
        sqlContent.append(_LIMIT).append(limit);

        return sqlContent.toString();
    }

    /**
     * 定义一个内部辅助类,作用是包装 SQL
     */
    class BoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }

    }

    private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new
                MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }


  @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties prop) {
        this.properties = prop;
    }
    

你可能感兴趣的:(MyBatis Interceptor修改SQL)