插件机制
https://mybatis.net.cn/configuration.html#plugins
MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
-
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
org.apache.ibatis.executor.Executor//执行器,调用StatementHandler -
ParameterHandler (getParameterObject, setParameters)
org.apache.ibatis.executor.parameter.ParameterHandler/SQL参数设置 -
ResultSetHandler (handleResultSets, handleOutputParameters)
org.apache.ibatis.executor.resultset.ResultSetHandler//SQL查询结果设置 -
StatementHandler (prepare, parameterize, batch, update, query)
org.apache.ibatis.executor.statement.StatementHandler//执行SQL
这些类中方法的细节可以通过查看每个方法的签名来发现,或者直接查看 MyBatis 发行包中的源代码。
使用插件是非常简单的,只需实现 Interceptor 接口,并指定想要拦截的方法签名即可。
一个插件示例
MyBatis 中的插件方法签名通常需要实现 org.apache.ibatis.plugin.Interceptor 接口
Object intercept(Invocation invocation):这是插件的核心方法,用于拦截 MyBatis 的方法调用。Object plugin(Object target):这个方法用于创建目标对象的代理对象,以便拦截目标对象的方法调用。void setProperties(Properties properties):通过这个方法,你可以从配置文件中获取插件的配置属性。
拦截org.apache.ibatis.executor.Executor#update 方法的代码如下:
// ExamplePlugin.java
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
private Properties properties = new Properties();
@Override
public Object intercept(Invocation invocation) throws Throwable {
// implement pre processing if need
Object returnObject = invocation.proceed();
// implement post processing if need
return returnObject;
}
@Override
public void setProperties(Properties properties) {
this.properties = properties;
}
}<plugins>
<plugin interceptor="org.mybatis.example.ExamplePlugin">
<property name="someProperty" value="100"/>
</plugin>
</plugins>上面的插件将会拦截在 Executor 实例中所有的 “update” 方法调用, 这里的 Executor 是负责执行底层映射语句的内部对象。