mybatis拦截器在执行前替换sql,记录一下踩的坑,希望能帮大家省点时间

防止忘了,记录一下

代码如下:

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.github.pagehelper.sqlsource.PageDynamicSqlSource;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.scripting.xmltags.SetSqlNode;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hand.framework.versioncontrol.annotation.VersionControl;

/**
 * @author Iwen
 * @version 1.0
 * @ClassName HftpVersionInterceptor
 * @description
 * @date 2020-10-20 11:14:55.
 * @since JDK 1.8
 */
@Intercepts(@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class HftpVersionInterceptor implements Interceptor {

    private Logger logger = LoggerFactory.getLogger(HftpVersionInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object param = invocation.getArgs()[1];

//        if (param == null || param.getClass().getAnnotation(VersionControl.class) == null) {
        if (param == null){
            return invocation.proceed();
        }

        Object result;
        SqlCommandType type = mappedStatement.getSqlCommandType();

        switch (type) {
            case SELECT:
                Class clazz = param.getClass();
                VersionControl versionControl = (VersionControl) clazz.getAnnotation(VersionControl.class);

                /*if (!versionControl.isEnabled()) {
                    return invocation.proceed();
                }*/

                // 获取sql
                String sql = getSqlByInvocation(invocation);

                // 按指定模式在字符串查找
                String pattern = "\\@\\@\\{(.*?)\\}\\@\\@";

                // 创建 Pattern 对象
                Pattern r = Pattern.compile(pattern);

                // 现在创建 matcher 对象
                Matcher m = r.matcher(sql);

                while (m.find()) {
                    String tableName = m.group();
                    logger.info("取得的表名为: " + tableName);
                    String newTableName = tableName.substring(3, tableName.length() - 3);
                    //待完成-----------------需要根据type来判断表名具体映射
                    sql = sql.replace(tableName, newTableName + "_t");
                }

                String newSql = sql;

                resetSql2Invocation(invocation,newSql);

                logger.info("querydata1 sql11:\n" + mappedStatement.getBoundSql(param).getSql());
                logger.info("querydata1 sql12:\n" + ((MappedStatement) invocation.getArgs()[0]).getBoundSql(param).getSql());

                result = invocation.proceed();
                break;
            default:
                result = invocation.proceed();
                break;
        }
        return result;
    }


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

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 获取sql语句
     *
     * @param invocation
     * @return
     */
    private String getSqlByInvocation(Invocation invocation) {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = ms.getBoundSql(parameterObject);
        return boundSql.getSql();
    }

    /**
     * 包装sql后,重置到invocation中
     *
     * @param invocation
     * @param sql
     * @throws SQLException
     */
    private void resetSql2Invocation(Invocation invocation, String sql) throws SQLException {
        final Object[] args = invocation.getArgs();
        MappedStatement statement = (MappedStatement) args[0];
        Object parameterObject = args[1];
        BoundSql boundSql = statement.getBoundSql(parameterObject);
        MappedStatement newStatement = newMappedStatement(statement, new BoundSqlSqlSource(boundSql));
        MetaObject msObject = MetaObject.forObject(newStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
        msObject.setValue("sqlSource.boundSql.sql", sql);
        args[0] = newStatement;
    }

    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) {
            StringBuilder keyProperties = new StringBuilder();
            for (String keyProperty : ms.getKeyProperties()) {
                keyProperties.append(keyProperty).append(",");
            }
            keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
            builder.keyProperty(keyProperties.toString());
        }
        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();
    }

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

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

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

总结

这种方式替换sql之后的sqlsource跟之前的结构不一样,虽然都实现了同样的接口,但是分页拦截器如果后执行,就会报错,所以这个拦截器需要设置在分页拦截器后面。需要注意的是,拦截器执行顺序与我们代码里写的顺序是反的,这个很多人都提到过,随便查一下就出来了。
我也尝试过用反射获取sql,然后同样用反射将sql放进去,但是替换之后执行的sql没发生变化,原因未知。
测试的时候,特别有分页的,会多次进入拦截器,仔细跟断点看看是不是自己想要的方法进来了。我传入的是dto,经过分页之后的的参数变成了HashMap,之前没有注意到,这样dto上的注解也就没了,我就直接return了,查了好久的原因,就看了分页count那次都替换成功了,真正查询的时候总没替换掉,其实就是进了拦截器,被自己return了。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值