一些收藏Mybatis

Mybatis自定义拦截器,实现拼接sql和修改2

2022-03-08  本文已影响0人  洛神灬殇

1.mybatis使用pageHelper分页功能受影响

       PageHelper的实现也是通过interceptor拦截实现的,所以二者如果在没有配置好拦截顺序的情况下,就会出现相互干扰的情况。这个需要在配置文件或者配置类中解决,拦截器是个集合,支持添加多个拦截器,其中拦截顺序也是需要注意的。

拦截器配置类如下:

import com.github.pagehelper.PageInterceptor;

import com.pingan.haofang.standard.common.interceptor.QueryByAppInterceptor;

import org.apache.ibatis.session.SqlSessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

import java.util.List;

import java.util.Properties;

@Configuration

public class MybatisPageHelp {

    @Autowired

    private List<SqlSessionFactory> sqlSessionFactoryList;

    /**

    * 接受分页插件额外的属性

     * @return

    */

    @Bean

    @ConfigurationProperties(prefix = "pagehelper")

    public Properties pageHelperProperties() {

        return new Properties();

    }

    @PostConstruct

    public void addPageInterceptor() {

        QueryByAppInterceptor queryByAppInterceptor = new QueryByAppInterceptor();

        PageInterceptor pageInterceptor = new PageInterceptor();

        Properties properties = new Properties();

        //先把一般方式配置的属性放进去

        properties.putAll(pageHelperProperties());

        //在把特殊配置放进去,close-conn 利用上面方式时,就是 close-conn 而不是 closeConn,所以需要额外的一步

        pageInterceptor.setProperties(properties);

        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {

            sqlSessionFactory.getConfiguration().addInterceptor(pageInterceptor);

            sqlSessionFactory.getConfiguration().addInterceptor(queryByAppInterceptor);

        }

    }

}

2.拦截器优化后代码:相比上一篇博客拦截器的实现这里不再利用反射改变sql语句,而是直接更换了查询语句对象。

package com.pingan.haofang.standard.common.interceptor;

import com.pingan.haofang.standard.common.annotation.interceptor.QueryConfigInterceptor;

import com.pingan.haofang.standard.common.context.ManageThreadContext;

import com.pingan.haofang.standard.common.context.ManageUser;

import com.pingan.haofang.standard.common.context.SpringContextHelper;

import com.pingan.haofang.standard.common.exception.PolicyException;

import com.pingan.haofang.standard.common.util.StringUtil;

import com.pingan.haofang.standard.configmapping.dao.ConfigMapDao;

import com.pingan.haofang.standard.configmapping.domain.ConfigMapping;

import org.apache.ibatis.cache.CacheKey;

import org.apache.ibatis.executor.Executor;

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 org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

import java.util.List;

import java.util.Properties;

@Intercepts(

        {

                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),

                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),

        }

)

public class QueryByAppInterceptor implements Interceptor {

    private static final Logger log = LoggerFactory.getLogger(QueryByAppInterceptor.class);

    static int MAPPED_STATEMENT_INDEX = 0;// 这是对应上面的args的序号

    private ConfigMapDao configMapDao;

    @Override

    public Object intercept(Invocation invocation) throws Throwable {

        Object result = null;

        ManageUser currentUser = ManageThreadContext.getManageVisitor();

        //当前用户为空不拦截

        if(currentUser == null){

            return invocation.proceed();

        }

        String appCode = currentUser.getCurrentApp();

        String version = currentUser.getCurrentAppVersion();

        //如果是管理员则不拦截

        if (currentUser.isAdmin()) {

            return invocation.proceed();

        }

        // 应用不存在不拦截

        if(StringUtil.isBlank(appCode) || StringUtil.isBlank(version)){

            return invocation.proceed();

        }

        configMapDao = SpringContextHelper.getBean(ConfigMapDao.class);

        Object[] args = invocation.getArgs();

        MappedStatement ms = (MappedStatement) args[0];

        //id为执行的mapper方法的全路径名,如com.uv.dao.UserMapper.insertUser

        String mId = ms.getId();

        //sql语句类型 select、delete、insert、update

        String sqlCommandType = ms.getSqlCommandType().toString();

        Object parameter = args[1];

        BoundSql boundSql  = ms.getBoundSql(parameter);;

        //获取到原始sql语句

        String sql = boundSql.getSql();

        //注解逻辑判断  添加注解了才拦截

        Class<?> classType = Class.forName(mId.substring(0, mId.lastIndexOf(".")));

        String mName = mId.substring(mId.lastIndexOf(".") + 1, mId.length());

        Method method1 = null;

        for (Method method : classType.getDeclaredMethods()) {

            if( !mName.equals(method.getName()) ){

                continue;

            }else{

                if(method.isAnnotationPresent(QueryConfigInterceptor.class)){

                    QueryConfigInterceptor interceptorAnnotation = method.getAnnotation(QueryConfigInterceptor.class);

                    if (interceptorAnnotation.flag()){

                        method1 = method;

                    }

                }

                break;

            }

        }

        if(method1 != null){

            //组装新的sql

            String mSql = this.process(sql, appCode, version);

            // 重新new一个查询语句对像

            BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), mSql, boundSql.getParameterMappings(), boundSql.getParameterObject());

            // 把新的查询放到statement里

            MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));

            for (ParameterMapping mapping : boundSql.getParameterMappings()) {

                String prop = mapping.getProperty();

                if (boundSql.hasAdditionalParameter(prop)) {

                    newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));

                }

            }

            final Object[] queryArgs = invocation.getArgs();

            queryArgs[MAPPED_STATEMENT_INDEX] = newMs;

//            //通过反射修改sql语句

//            Field field = boundSql.getClass().getDeclaredField("sql");

//            field.setAccessible(true);

//            field.set(boundSql, mSql);

        }

        return invocation.proceed();

    }

    private String process(String sql, String appCode, String version ){

        String msql="";

        //此处隐去与拦截器不相关的sql处理相关逻辑

        return mSql;

    }

    public static class BoundSqlSqlSource implements SqlSource {

        private BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {

            this.boundSql = boundSql;

        }

        public BoundSql getBoundSql(Object parameterObject) {

            return boundSql;

        }

    }

    private MappedStatement copyFromMappedStatement(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) {

        return Plugin.wrap(target, this);

    }

    @Override

    public void setProperties(Properties properties) {

    }

}

3.多个拦截器执行有顺序之分,具体可以从官网介绍中寻找答案

https://pagehelper.github.io/docs/interceptor/

4.许多小伙伴反应按照第一篇博客操作,拦截器没生效,最大的可能就是:拦截器没有注入。第一个版本是在拦截器类上添加@Component注解,但是这个会导致pageHelper分页发生冲突,所以我们需要在配置类中将拦截器注入,并且由添加顺序来控制拦截顺序,具体代码看第2点。

上一篇下一篇

猜你喜欢

热点阅读