MyBatis拦截器介绍
MyBatis提供了一种插件(plugin)的功能,虽然叫做插件,但其实这是拦截器功能。那么拦截器拦截MyBatis中的哪些内容呢?
我们进入官网看一看:
MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)
我们看到了可以拦截Executor接口的部分方法,比如update,query,commit,rollback等方法,还有其他接口的一些方法等。
总体概括为:
拦截执行器的方法
拦截参数的处理
拦截结果集的处理
拦截Sql语法构建的处理
拦截器的使用
首先我们看下MyBatis拦截器的接口定义:
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
比较简单,只有3个方法。 MyBatis默认没有一个拦截器接口的实现类,开发者们可以实现符合自己需求的拦截器。
Plugin方法:是拦截器用于封装目标对象,同过该方法可以返回目标对象本身,也可以返回它的一个代理。当返回代理时,我们可以对其中的方法进行拦截来调用intercept方法,也可以调用其他方法。
SetProperties方法:用于在mybatis配置文件中指定一些属性。
Interceptor方法:是拦截时需要执行的方法(重要实现)。
步骤:
1、创建拦截器类实现实现org.apache.ibatis.plugin.Interceptor接口
2、为自定义拦截器类添加注解org.apache.ibatis.plugin.Intercepts
例如:
@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}
),
@Signature(
type = Executor.class,
method = "update",
args = {MappedStatement.class, Object.class}
)
})
@Component
public class MybatisInterceptor implements Interceptor {
@Intercepts:标明该类是一个拦截器
@Signature:可以理解为一个拦截项
type:指定拦截的接口类型
method:指定拦截的方法类型
运行被拦截的方法有如下
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed),对执行器进行拦截,可以对sql执行前后,做一些特殊操作
ParameterHandler (getParameterObject, setParameters),对参数处理器进行拦截,对参数做处理
ResultSetHandler (handleResultSets, handleOutputParameters)对结果集做处理
StatementHandler (prepare, parameterize, batch, update, query)