mybatis–基础–2.6–xml配置–插件(plugins)
代码地址
https://gitee.com/DanShenGuiZu/learnDemo/tree/mysql_mybaties_DB/mybatis-learn-master
1、插件(plugins)
- 允许你对映射语句执行过程中的某一点进行拦截调用。
- 默认情况下,MyBatis允许使用插件来拦截方法调用
- 试图修改或重写已有方法的行为时,很可能会破坏MyBatis的核心模块,使用插件的时候要特别当心。
- 除了用插件来修改MyBatis核心行为以外,还可以继承配置类后覆盖其中的某个方法,再把它传递到SqlSessionFactoryBuilder.build(myConfig)方法即可。这可能会极大影响MyBatis的行为,务请慎之又慎。
2、拦截方法
2.1、Executor
- update
- query
- flushStatements
- commit
- rollback
- getTransaction
- close
- isClosed
2.2、ParameterHandler
- getParameterObject
- setParameters
2.3、ResultSetHandler
- handleResultSets
- handleOutputParameters
2.4、StatementHandler
- prepare
- parameterize
- batch
- update
3、案例
3.1、核心代码
package com.cl.mybatis.learn.day08;
import java.sql.Connection;
import java.util.Properties;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.*;
@Intercepts({
@Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class })})
public class ExamplePlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation)throws Throwable {
StatementHandler statementHandler =(StatementHandler)invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
System.out.println("拦截的 sql::" + sql);
return invocation.proceed();
}
@Override
public Object plugin(Object target){
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties){
String dialect = properties.getProperty("dialect");
System.out.println("获取的属性为::" + dialect);
}
}
<plugins>
<plugin interceptor="com.cl.mybatis.learn.day08.ExamplePlugin">
<property name="dialect" value="mysql" />
</plugin>
</plugins>