Mybatis 插件
引言
Mybatis插件又叫拦截器
MyBatis 允许你在映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
通过 MyBatis 提供的强大机制,使用插件是非常简单的,只需实现 Interceptor 接口,并指定想要拦截的方法签名即可。
// ExamplePlugin.java
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
private Properties properties = new Properties();
public Object intercept(Invocation invocation) throws Throwable {
Object target = invocation.getTarget(); //被代理对象
Method method = invocation.getMethod(); //代理方法
Object[] args = invocation.getArgs(); //方法参数
// do something ...... 方法拦截前执行代码块
Object result = invocation.proceed();
// do something .......方法拦截后执行代码块
return result;
}
public Object plugin(Object target){
return Plugin.wrap(target,this);
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}
我们先看下Interceptor接口的三个方法:
intercept:实现自己拦截后的逻辑,可以从invocation中拿到代理对象,最后调用invocation.proceed()返回结果
plugin:生成代理对象
setProperties:设置一些属性变量
在xml文件中配置插件
<!-- mybatis-config.xml -->
<plugins>
<plugin interceptor="org.mybatis.example.ExamplePlugin">
<property name="someProperty" value="100"/>
</plugin>
</plugins>
原理
Mybatis插件的设计原理是动态代理和责任链模式。简单的说就是原对象被拦截包装成了代理对象,我们执行的也是代理对象的方法。
我们可以看下代理对象是如何生成的:
Executor代理对象
ParameterHandler代理对象:
ResultSetHandler代理对象:
StatementHandler代理对象:
观察源码,发现这些可拦截的类对应的对象生成都是通过InterceptorChain的pluginAll方法来创建的,进一步观察pluginAll方法,如下:
遍历所有拦截器,调用拦截器的plugin方法生成代理对象,注意生成代理对象重新赋值给target,所以如果有多个拦截器的话,生成的代理对象会被另一个代理对象代理,从而形成一个代理链条,执行的时候,依次执行所有拦截器的拦截逻辑代码;
接下来看一下我们在编写拦截器的时候,一个典型的plugin方法实现方式,如下:
再进一步查看wrap方法,如下:
典型的动态代理实现,调用的是Proxy.newProxyInstance方法来生成代理对象。
Interceptor
@Intercepts
用来定义在哪里进行拦截。
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class,
ResultHandler.class, CacheKey.class, BoundSql.class}))
type:拦截哪个接口
method:拦截哪个方法
args:方法的参数类型
示例
这里写一个springboot+mybatis 自定义插件打印sql日志(实际中不需要这样做,直接使用mybatis的日志功能就可以了,这里只是为了演示)
@Intercepts({
@Signature(type= Executor.class, method = "query",
//要注意方法的参数一定要和类里方法参数对应,可以进类里去看
//注意这里必须是java.lang.Object.class,一不小心就会错
args = { MappedStatement.class,java.lang.Object.class, RowBounds.class, ResultHandler.class}),
@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,java.lang.Object.class})})
public class logPlugins implements Interceptor {
private Properties properties = new Properties();
@Override
public java.lang.Object intercept(Invocation invocation) throws Throwable {
//获得第一个参数MappedStatement,里面存储着sql语句
MappedStatement mappedStatement =(MappedStatement) invocation.getArgs()[0];
Object parm=null;
if(invocation.getArgs().length>1){
parm=invocation.getArgs()[1];
}
BoundSql boundSql = mappedStatement.getBoundSql(parm);
Configuration configuration = mappedStatement.getConfiguration();
java.lang.Object proceed = invocation.proceed();
String sql = getSql(configuration, boundSql);
System.out.println(sql);
return proceed;
}
@Override
public java.lang.Object plugin(java.lang.Object target) {
return Plugin.wrap(target,this);
}
@Override
public void setProperties(Properties properties) {
this.properties=properties;
}
private String getSql(Configuration configuration, BoundSql boundSql) {
Object parameterObject = boundSql.getParameterObject();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
if (parameterObject == null || parameterMappings.size() == 0) {
return sql;
}
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = boundSql.getAdditionalParameter(propertyName);
sql = sql.replaceFirst("\\?", getParameterValue(obj));
}
}
}
return sql;
}
private String getParameterValue(Object obj) {
String value = null;
if (obj instanceof String) {
value = "'" + obj.toString() + "'";
} else if (obj instanceof Date) {
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
value = "'" + formatter.format(obj) + "'";
} else {
if (obj != null) {
value = obj.toString();
} else {
value = "";
}
}
return value;
}
}
修改mybatis-config.xml(我把它放在了resources/config/mybatis-config.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<plugin interceptor="com.wang.demo.plugins.logPlugins"></plugin>
</plugins>
</configuration>
修改properties配置文件:
mybatis.config-location=classpath:config/mybatis-config.xml
mybatis.type-aliases-package=com.wang.demo.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
需要注意的点:
1.注意对应的类所在的包,不要导错了,尤其是Object,一定要是java.lang.object,我第一次编写时遇到了Executor没有query这个方法,找了半天,原来是object导错包了!
2.不要忘了修改mybatis配置文件,把插件设置进去
3.MappedStatement.class这个类封装了有关sql语句的部分,Object.class则封装了我们传入给sql语句的参数,RowBounds.class和分页相关,ResultHandler.class和sql结果相关
4.你自定义的逻辑方法在invocation.proceed()的前后顺序 取决于 你究竟是想在sql语句执行之前 执行你的方法,还是在sql语句执行之后执行你的方法。在这个示例中,我是先执行sql语句再执行打印日志。
5.如果你的mybatis.mapper-locations配置的是*.xml的话,就不能把其他xml文件放在mapper.xml的目录下,spring会将该目录下所有xml文件当场mapper解析,解析不到就会报错。因此你可以放在别的目录下,或者把mybatis.mapper-locations配置为*Mapper.xml