Mybatis的插件,主要用于在执行sql前后,对sql进行封装加工,或者在sql执行后,对数据进行加工处理。常用于一些公共数据操作处理,例如:
指定需要拦截的方法,通过方法签名来指定,方法签名即指定哪个类的哪个方法+方法参数。这里的类不能随便写,只能从以下几个类中选,也就是说,MyBatis 插件可以拦截四大对象中的任意一个。
我们来看以下mybatisplus的插件配置的签名:
@Intercepts(
{
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}),
@Signature(type = StatementHandler.class, method = "getBoundSql", args = {}),
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@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}),
}
)
public class MybatisPlusInterceptor implements Interceptor {
//...
}
type指定四大类型中的任意一个,method指定拦截类型中方法,args指定方法参数。例如:
@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
指定了拦截StatementHandler的prepare方法,方法有两个参数,一个是Connection类型,另一个是Integer类型。
public interface StatementHandler {
Statement prepare(Connection connection, Integer transactionTimeout)
throws SQLException;
//....
}
在 MyBatis 中开发插件,需要实现 Interceptor 接口。接口的定义如下:
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
创建个类实现Interceptor接口,并且在实现类上指定方法签名即可。
最后需要在mybatis配置文件中配置插件
最后建议看一下MybatisPlusInterceptor的实现,里面还使用到了责任链设计模式。