mybatis拦截器详解_mybatis过滤器

mybatis拦截器详解_mybatis过滤器原文https://blog.csdn.net/weixin_39494923/article/details/91534658一.背景在很多业务场景下我们需要去拦截sql,达到不入侵原有代码业务处理一些东西,比如:分页操作,数据权限过滤操作,SQL执行时间性能监控等等,这里我们就可以用到Mybatis的拦截器Interceptor二.Mybatis核心对象介绍从MyBatis代码实现的角度来看,MyBatis的主要的核心部件有以下几个:Configuration初始化基础配置,比如MyBat

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

原文https://blog.csdn.net/weixin_39494923/article/details/91534658

一.背景

在很多业务场景下我们需要去拦截sql,达到不入侵原有代码业务处理一些东西,比如:分页操作,数据权限过滤操作,SQL执行时间性能监控等等,这里我们就可以用到Mybatis的拦截器Interceptor

二.Mybatis核心对象介绍

从MyBatis代码实现的角度来看,MyBatis的主要的核心部件有以下几个:

  • Configuration 初始化基础配置,比如MyBatis的别名等,一些重要的类型对象,如,插件,映射器,ObjectFactory和typeHandler对象,MyBatis所有的配置信息都维持在Configuration对象之中
  • SqlSessionFactory SqlSession工厂
  • SqlSession 作为MyBatis工作的主要顶层API,表示和数据库交互的会话,完成必要数据库增删改查功能
  • Executor MyBatis执行器,是MyBatis 调度的核心,负责SQL语句的生成和查询缓存的维护
  • StatementHandler 封装了JDBC Statement操作,负责对JDBC statement 的操作,如设置参数、将Statement结果集转换成List集合。
  • ParameterHandler 负责对用户传递的参数转换成JDBC Statement 所需要的参数,
  • ResultSetHandler 负责将JDBC返回的ResultSet结果集对象转换成List类型的集合;
  • TypeHandler 负责java数据类型和jdbc数据类型之间的映射和转换
  • MappedStatement MappedStatement维护了一条<select|update|delete|insert>节点的封装,
  • SqlSource 负责根据用户传递的parameterObject,动态地生成SQL语句,将信息封装到BoundSql对象中,并返回
  • BoundSql 表示动态生成的SQL语句以及相应的参数信息

三. Mybatis执行概要图

img

四.MyBatis 拦截器原理实现

  1. Mybatis支持对Executor、StatementHandler、PameterHandler和ResultSetHandler 接口进行拦截,也就是说会对这4种对象进行代理
  2. 首先从配置文件解析开始
  • 通过SqlSessionFactoryBean去构建Configuration添加拦截器并构建获取SqlSessionFactory
/** * {@code FactoryBean} that creates an MyBatis {@code SqlSessionFactory}. * This is the usual way to set up a shared MyBatis {@code SqlSessionFactory} in a Spring application context; * the SqlSessionFactory can then be passed to MyBatis-based DAOs via dependency injection. * * Either {@code DataSourceTransactionManager} or {@code JtaTransactionManager} can be used for transaction * demarcation in combination with a {@code SqlSessionFactory}. JTA should be used for transactions * which span multiple databases or when container managed transactions (CMT) are being used. * * @author Putthibong Boonbong * @author Hunter Presnall * @author Eduardo Macarron * @author Eddú Meléndez * @author Kazuki Shimizu * * @see #setConfigLocation * @see #setDataSource */
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> { 
   
 
    private static final Log LOGGER = LogFactory.getLog(SqlSessionFactoryBean.class);
 
    private Resource configLocation;
 
    private Configuration configuration;
 
    private Resource[] mapperLocations;
 
    private DataSource dataSource;
 
    private TransactionFactory transactionFactory;
 
    private Properties configurationProperties;
 
    private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
 
    // ... 此处省略部分源码
 
    /** * Build a {@code SqlSessionFactory} instance. * * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a * {@code SqlSessionFactory} instance based on an Reader. * Since 1.3.0, it can be specified a {@link Configuration} instance directly(without config file). * * @return SqlSessionFactory * @throws IOException if loading the config file failed */
    protected SqlSessionFactory buildSqlSessionFactory() throws IOException { 
   
 
 
        Configuration configuration;
        // 根据配置信息构建Configuration实体类
        XMLConfigBuilder xmlConfigBuilder = null;
        if (this.configuration != null) { 
   
            configuration = this.configuration;
            if (configuration.getVariables() == null) { 
   
                configuration.setVariables(this.configurationProperties);
            } else if (this.configurationProperties != null) { 
   
                configuration.getVariables().putAll(this.configurationProperties);
            }
        } else if (this.configLocation != null) { 
   
            xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
            configuration = xmlConfigBuilder.getConfiguration();
        } else { 
   
            if (LOGGER.isDebugEnabled()) { 
   
                LOGGER.debug("Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
            }
            configuration = new Configuration();
            if (this.configurationProperties != null) { 
   
                configuration.setVariables(this.configurationProperties);
            }
        }
 
        // ... 此处省略部分源码
 
        if (hasLength(this.typeAliasesPackage)) { 
   
            String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
                    ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
            for (String packageToScan : typeAliasPackageArray) { 
   
                configuration.getTypeAliasRegistry().registerAliases(packageToScan,
                        typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
                if (LOGGER.isDebugEnabled()) { 
   
                    LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases");
                }
            }
        }
 
        if (!isEmpty(this.typeAliases)) { 
   
            for (Class<?> typeAlias : this.typeAliases) { 
   
                configuration.getTypeAliasRegistry().registerAlias(typeAlias);
                if (LOGGER.isDebugEnabled()) { 
   
                    LOGGER.debug("Registered type alias: '" + typeAlias + "'");
                }
            }
        }
        // 查看是否注入拦截器,有的话添加到Interceptor集合里面
        if (!isEmpty(this.plugins)) { 
   
            for (Interceptor plugin : this.plugins) { 
   
                configuration.addInterceptor(plugin);
                if (LOGGER.isDebugEnabled()) { 
   
                    LOGGER.debug("Registered plugin: '" + plugin + "'");
                }
            }
        }
 
        // ... 此处省略部分源码
 
        return this.sqlSessionFactoryBuilder.build(configuration);
    }
 
    // ... 此处省略部分源码
}

  • 通过原始的XMLConfigBuilder 构建configuration添加拦截器
public class XMLConfigBuilder extends BaseBuilder { 
   
    //解析配置
    private void parseConfiguration(XNode root) { 
   
        try { 
   
            //省略部分代码
            pluginElement(root.evalNode("plugins"));
 
        } catch (Exception e) { 
   
            throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
        }
    }
 
    private void pluginElement(XNode parent) throws Exception { 
   
        if (parent != null) { 
   
            for (XNode child : parent.getChildren()) { 
   
                String interceptor = child.getStringAttribute("interceptor");
                Properties properties = child.getChildrenAsProperties();
                Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
                interceptorInstance.setProperties(properties);
                //调用InterceptorChain.addInterceptor
                configuration.addInterceptor(interceptorInstance);
            }
        }
    }
}

上面是两种不同的形式构建configuration并添加拦截器interceptor,上面第二种一般是以前XML配置的情况,这里主要是解析配置文件的plugin节点,根据配置的interceptor 属性实例化Interceptor 对象,然后添加到Configuration 对象中的InterceptorChain 属性中

3.定义了拦截器链,初始化配置文件的时候就把所有的拦截器添加到拦截器链中

org.apache.ibatis.plugin.InterceptorChain 源代码如下:

public class InterceptorChain { 
   
 
 
  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
 
  public Object pluginAll(Object target) { 
   
    //循环调用每个Interceptor.plugin方法
    for (Interceptor interceptor : interceptors) { 
   
      target = interceptor.plugin(target);
    }
    return target;
  }
   // 添加拦截器
  public void addInterceptor(Interceptor interceptor) { 
   
    interceptors.add(interceptor);
  }
  
  public List<Interceptor> getInterceptors() { 
   
    return Collections.unmodifiableList(interceptors);
  }
 
}

4.从以下代码可以看出mybatis 在实例化Executor、ParameterHandler、ResultSetHandler、StatementHandler四大接口对象的时候调用interceptorChain.pluginAll() 方法插入进去的。其实就是循环执行拦截器链所有的拦截器的plugin() 方法,
mybatis官方推荐的plugin方法是Plugin.wrap() 方法,这个类就是我们上面的TargetProxy类
org.apache.ibatis.session.Configuration 类,其代码如下:

public class Configuration { 
   
 
    protected final InterceptorChain interceptorChain = new InterceptorChain();
    //创建参数处理器
    public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { 
   
        //创建ParameterHandler
        ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
        //插件在这里插入
        parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
        return parameterHandler;
    }
 
    //创建结果集处理器
    public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
                                                ResultHandler resultHandler, BoundSql boundSql) { 
   
        //创建DefaultResultSetHandler
        ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
        //插件在这里插入
        resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
        return resultSetHandler;
    }
 
    //创建语句处理器
    public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { 
   
        //创建路由选择语句处理器
        StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
        //插件在这里插入
        statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
        return statementHandler;
    }
 
    public Executor newExecutor(Transaction transaction) { 
   
        return newExecutor(transaction, defaultExecutorType);
    }
 
    //产生执行器
    public Executor newExecutor(Transaction transaction, ExecutorType executorType) { 
   
        executorType = executorType == null ? defaultExecutorType : executorType;
        //这句再做一下保护,囧,防止粗心大意的人将defaultExecutorType设成null?
        executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
        Executor executor;
        //然后就是简单的3个分支,产生3种执行器BatchExecutor/ReuseExecutor/SimpleExecutor
        if (ExecutorType.BATCH == executorType) { 
   
            executor = new BatchExecutor(this, transaction);
        } else if (ExecutorType.REUSE == executorType) { 
   
            executor = new ReuseExecutor(this, transaction);
        } else { 
   
            executor = new SimpleExecutor(this, transaction);
        }
        //如果要求缓存,生成另一种CachingExecutor(默认就是有缓存),装饰者模式,所以默认都是返回CachingExecutor
        if (cacheEnabled) { 
   
            executor = new CachingExecutor(executor);
        }
        //此处调用插件,通过插件可以改变Executor行为
        executor = (Executor) interceptorChain.pluginAll(executor);
        return executor;
    }
}

5.Mybatis的Plugin动态代理

org.apache.ibatis.plugin.Plugin 源代码如下

public class Plugin implements InvocationHandler { 
   
 
    public static Object wrap(Object target, Interceptor interceptor) { 
   
    //从拦截器的注解中获取拦截的类名和方法信息
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    //取得要改变行为的类(ParameterHandler|ResultSetHandler|StatementHandler|Executor)
    Class<?> type = target.getClass();
    //取得接口
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    //产生代理,是Interceptor注解的接口的实现类才会产生代理
    if (interfaces.length > 0) { 
   
      return Proxy.newProxyInstance(type.getClassLoader(),interfaces,new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }
    
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
   
    try { 
   
      //获取需要拦截的方法
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      //是Interceptor实现类注解的方法才会拦截处理
      if (methods != null && methods.contains(method)) { 
   
        //******调用Interceptor.intercept,也即插入了我们自己的逻辑********
        return interceptor.intercept(new Invocation(target, method, args));
      }
      //最后还是执行原来逻辑
        return method.invoke(target, args);
    } catch (Exception e) { 
   
        throw ExceptionUtil.unwrapThrowable(e);
    }
  }
    
  //取得签名Map,就是获取Interceptor实现类上面的注解,要拦截的是那个类(Executor 
  //,ParameterHandler, ResultSetHandler,StatementHandler)的那个方法 
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) { 
   
    //取Intercepts注解,例子可参见ExamplePlugin.java
    Intercepts interceptsAnnotation =interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    //必须得有Intercepts注解,没有报错
    if (interceptsAnnotation == null) { 
   
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
    //value是数组型,Signature的数组
      Signature[] sigs = interceptsAnnotation.value();
    //每个class里有多个Method需要被拦截,所以这么定义
      Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
     for (Signature sig : sigs) { 
   
      Set<Method> methods = signatureMap.get(sig.type());
        if (methods == null) { 
   
          methods = new HashSet<Method>();
          signatureMap.put(sig.type(), methods);
      }
      try { 
   
         Method method = sig.type().getMethod(sig.method(), sig.args());
         methods.add(method);
      } catch (NoSuchMethodException e) { 
   
         throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
      }
    }
    return signatureMap;
  }
    
 //取得接口
 private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) { 
   
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
      while (type != null) { 
   
        for (Class<?> c : type.getInterfaces()) { 
   
        //拦截其他的无效
        if (signatureMap.containsKey(c)) { 
   
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[interfaces.size()]);
  }
}

6.我们自己实现的拦截器

@Slf4j
@Component
@Intercepts({ 
   @Signature(method = "prepare", type = StatementHandler.class, args = { 
   Connection.class, Integer.class}),
            @Signature(method = "query", type = Executor.class, args = { 
   MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})})
@SuppressWarnings("unchecked")
public class SqliteDataSourceInterceptor implements Interceptor { 
   
 
    @Override
    public Object plugin(Object target) { 
   
        // 调用插件
        return Plugin.wrap(target, this);
    }
 
    @Override
    public void setProperties(Properties properties) { 
   
    }
 
    @Override
    public Object intercept(Invocation invocation) throws Exception { 
   
        // 该方法写入自己的逻辑
        if (invocation.getTarget() instanceof StatementHandler) { 
   
            String dataSoureType = DynamicDataSourceContextHolder.getDateSoureType();
            // judge dataSource type ,because sqlite can't use internal.core_project this express
            // so we need to add "" for it or delete this 'internal.'
            if (DataSourceType.SQLITE.name().equals(dataSoureType)) { 
   
                RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();
                StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");
                BoundSql boundSql = delegate.getBoundSql();
                String sql = boundSql.getSql();
                sql = sql.replace("internal.", " ");
                ReflectUtil.setFieldValue(boundSql, "sql", sql);
            }
        }
        // SQL execute start time
        long startTimeMillis = System.currentTimeMillis();
        // get execute result
        Object proceedReslut = invocation.proceed();
        // SQL execute end time
        long endTimeMillis = System.currentTimeMillis();
        log.debug("<< ==== sql execute runnung time:{} millisecond ==== >>", (endTimeMillis - startTimeMillis));
        return proceedReslut;
    }
}

Mybatis拦截器用到责任链模式+动态代理+反射机制;

通过上面的分析可以知道,所有可能被拦截的处理类都会生成一个代理类,如果有N个拦截器,就会有N个代理,层层生成动态代理是比较耗性能的。而且虽然能指定插件拦截的位置,但这个是在执行方法时利用反射动态判断的,初始化的时候就是简单的把拦截器插入到了所有可以拦截的地方。所以尽量不要编写不必要的拦截器;

附:如果采用SqlSessionFactoryBean的形式配置拦截器不起作用,需要在SqlSessionFactoryBean设置添加即可,如下红框框

img

个人博客:https://www.xiaoxuya.top/

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/195627.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 华为裁员34岁以上程序员,90后的中年危机,即将在职场引爆

    华为裁员34岁以上程序员,90后的中年危机,即将在职场引爆去年,一条职场潜规则走红网络:不要大声责骂年轻人,他们会立刻辞职的,但是你可以往死里骂那些中年人,尤其是有车有房有娃的那些。真实感受到程序员的中年危机在中国,除了从BAT出来的牛人,一般经理层到35岁,总监层到40岁,往后机会真的会少很多了,不是你能不能干的问题,是别人不给机会你干的问题,不要想着什么外国人可以干到50、60,你就要死磕到底,希望后来者早有打算,不要到最后尴尬的时…

  • Linux Redhat 7.6 操作系统 下载安装详解「建议收藏」

    Linux Redhat 7.6 操作系统 下载安装详解「建议收藏」redhat系统镜像分享[百度网盘分享]链接:https://pan.baidu.com/s/1U0SUh7qmLGfpLN5Fqb4Wgg提取码:bpwdredhat7.6版本安装详解

  • mac idea 激活码_最新在线免费激活

    (mac idea 激活码)本文适用于JetBrains家族所有ide,包括IntelliJidea,phpstorm,webstorm,pycharm,datagrip等。IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.cn/100143.html…

  • 如何测试ntp时间服务器

    C:\DocumentsandSettings\Administrator>w32tm/stripchart/computer:aisa.pool.ntp.orgTrackingaisa.pool.ntp.org[180.168.41.175].Thecurrenttimeis2012-3-715:35:23(localtime).15:35:23err

  • pychrm激活码【注册码】

    pychrm激活码【注册码】,https://javaforall.cn/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

  • opencv lsd算法_opencv目标识别

    opencv lsd算法_opencv目标识别最小二乘法的概念最小二乘法要关心的是对应的costfunction是线性还是非线性函数,不同的方法计算效率如何,要不要求逆,矩阵的维数一般都是过约束,方程式的数目多于未知的参数数目。最小二乘法的目标:求误差的最小平方和,根据costfunction的对应有两种:线性和非线性(取决于对应的残差(residual)是线性的还是非线性的)。线性最小二乘的解是closed-formsolution …

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号