前言:
前面我们分析了 MyBatis 插件(拦截器)的原理,本篇分享 MyBatis 插件(拦截器)的实战。
Mybatis 相关知识传送门
MyBatis 源码分析–SqlSessionFactory
MyBatis 源码分析-- getMapper(获取Mapper)
MyBatis 源码分析-- SQL请求执行流程( Mapper 接口方法的执行的过程)
创建自定义 MyBatis 插件(拦截器)
创建自定义 MyBatis 插件(拦截器)需要实现 org.apache.ibatis.plugin.Interceptor 接口,在类上添加 @Intercepts 注解,前文我们已经说了MyBatis 插件(拦截器)默认可以拦截的类型有四种,分别是 Executor、StatementHandler、ParameterHandler、ResultSetHandler,对自定义 插件(拦截器)必须使用 MyBatis 提供的 @Intercepts 注解来表明我们要拦截的是哪一种获几种接口,如下:
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {
MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class,method = "update",args = {
MappedStatement.class, Object.class})
@Signature(type = StatementHandler.class, method = "prepare", args = {
Connection.class, Integer.class}),
@Signature(type = ParameterHandler.class, method = "setParameters", args = {
PreparedStatement.class}),
@Signature(type = ResultSetHandler.<