目录:
Mybatis拦截器 可以帮助我们在执行sql语句过程中增加插件以实现一些通用的逻辑,比如对查询sql分页、数据权限处理等。
允许使用插件拦截的方法调用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
各方法的具体作用可以通过 Mybatis之sqlSession调用链分析 进行了解。
方法调用时加载拦截器链的总体时序图如下:
一. 建立拦截器链
1. 创建对象
建立拦截器对象,对Executor接口的实现类上的update方法调用进行拦截:
// ExamplePlugin.java
@Intercepts({
@Signature(
type= Executor.class,
method = "update",
args = {
MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
return invocation.proceed();
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
Mybaits中通过注解Intercepts来设定当前拦截器是否对被拦截的请求进行处理,例子中的注解指定对Executor的所有update方法进行拦截处理。
- Intercepts
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Intercepts {
Signature[] value();
}
- Signature
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({
})
public @interface S