Mybatis拦截器(一)

拦截器需要实现 interceptor接口

public interface Interceptor {
//3 对目标对象拦截进行处理的内容 
  Object intercept(Invocation invocation) throws Throwable;
//2 确定是否执行拦截并返回一个拦截对象 拦截器连InterceptorChain 会根据返回的值执行 
//调用
Proxy.newProxyInstance(type.getClassLoader(),interfaces,new Plugin(target, interceptor, signatureMap)); 创建代理对象

Object plugin(Object target);
// 1 setProperties方法是用于在Mybatis配置文件中指定一些属性的
  void setProperties(Properties properties);
}

拦截器执行顺序:
1 先执行setProperties
<plugin interceptor="com.tiantian.mybatis.interceptor.MyInterceptor">
<property name="prop1" value="prop1"/>
<property name="prop2" value="prop2"/>
</plugin>
根据property 属性设置setProperties

2新建可拦截对象的时候会调用plugin方法来决定是返回目标对象本身还是代理对象。

3 当StatementHandler 代理对象在执行方法prepare参数类型为java.sql.Connection.class 的时候就会触发当前的拦截器的intercept方法进行拦截
最后执行intercept

拦截器注解

@Intercepts({@org.apache.ibatis.plugin.Signature(type=StatementHandler.class, method="prepare", args={java.sql.Connection.class})})
当mybatis是 的时候返回代理对象,其他返回目标对象
type:是要拦截的对象 ,method 拦截什么方法,args 方法的参数是什么

mybatis 能拦截以下四个对象:  executor, statementHandler,parameterHandler,resultHandler对象

executor
(1、根据传递的参数,完成SQL语句的动态解析,生成BoundSql对象,供StatementHandler使用;

(2、为查询创建缓存,以提高性能(具体它的缓存机制不是本文的重点,我会单独拿出来跟大家探讨,感兴趣的读者可以关注我的其他博文);

(3、创建JDBC的Statement连接对象,传递给StatementHandler对象,返回List查询结果。

StatementHandler :就是和数据库对话
(1、当我们需要改变sql的时候,显然我们要在预编译SQL(prepare方法前加入修改的逻辑),功能:分页,机构过滤等需要修改原始sql 

(2、当我们需要修改参数的时候我们可以在调用parameterize方法前修改逻辑。或者使用ParameterHandler来改造设置参数。

parameterHandler

(1、ParameterHandler是用来设置参数规则的,setParameters()是设置参数的,相当于对一条sql所有的参数都执行ps.setXXX(value);

resultHandler:将sql执行返回的结果封装转换为java实体类

 

猜你喜欢

转载自www.cnblogs.com/fanBlog/p/9510405.html