mybatis拦截器(一)

54

@[toc]

一、MyBatis拦截器介绍

mybatis拦截器可以拦截如下4中类型

  • Executor sql的内部执行器
  • ParameterHandler 拦截参数的处理
  • StatementHandler 拦截sql的构建
  • ResultSetHandler 拦截结果的处理

这4中不同类型的拦截器的拦截顺序为从上到下的顺序,即
Executor -> ParameterHandler -> StatementHandler -> ResultSetHandler

如果相同类型的拦截器,比如Executor类型的拦截器有两个,则执行顺序为将拦截器添加到SqlSessionFactory的逆向顺序执行

比如SqlSessionFactory中先添加了Executor类型的A拦截器,在添加了Executor类型的B拦截器,则会先执行B拦截器,在执行A拦截器

二、创建拦截器

这里因为我的业务需求是只需要拦截查询语句,所以我用到的是Executor拦截器

@Intercepts:申明这是一个拦截器,并配置拦截器信息
@Signature:拦截配置,type为上述介绍的拦截类型,method为需要拦截Executor接口中的什么方法,args为填写method的方法参数,因为存在方法重载,所以需要指定参数,下文中将两个query同时拦截

@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})
})
// 配置为组件让spring加载后会自动加入到SqlSessionFactory中生效
@Component
public class DeptDataScopeInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();

        // ------自定义的拦截业务开始------

        // ------自定义的拦截业务结束------
        return invocation.proceed();
    }

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

    @Override
    public void setProperties(Properties properties) {

    }

}