1. 拦截器注解
1. mybatis自定义拦截器实现步骤:
- 实现
org.apache.ibatis.plugin.Interceptor
接口。 - 添加拦截器注解
org.apache.ibatis.plugin.Intercepts
。 - 配置文件中添加拦截器。
2. 在mybatis中可被拦截的类型有四种(按照拦截顺序):
- Executor:拦截执行器的方法。
- ParameterHandler:拦截参数的处理。
- ResultHandler:拦截结果集的处理。
- StatementHandler:拦截Sql语法构建的处理。
具体规则如下:
@Intercepts({
@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
@Signature(type = StatementHandler.class, method = "update", args = {Statement.class}),
@Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})
})
- @Intercepts:标识该类是一个拦截器;
- @Signature:指明自定义拦截器需要拦截哪一个类型,哪一个方法;
2.1 type:对应四种类型中的一种;
2.2 method:对应接口中的哪类方法(因为可能存在重载方法);
2.3 args:对应哪一个方法;
2. 拦截器可拦截的方法:
拦截的类 | 拦截的方法 |
---|---|
Executor | update, query, flushStatements, commit, rollback,getTransaction, close, isClosed |
ParameterHandler | getParameterObject, setParameters |
StatementHandler | prepare, parameterize, batch, update, query |
ResultSetHandler | handleResultSets, handleOutputParameters |