先上代码:
package com.belizer.mybatis.simple;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;
@Intercepts({@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class,Object.class, RowBounds.class, ResultHandler.class}
)})
public class UtilInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement=(MappedStatement) invocation.getArgs()[0];
BoundSql boundSql =mappedStatement.getBoundSql( invocation.getArgs()[1]);
System.out.format("plugin output sql = %s , param=%s",boundSql.getSql(),boundSql.getParameterObject());
System.out.println();
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}
@Override
public void setProperties(Properties properties) {
}
}
@Intercepts({@Signature( type = Executor.class, method = "query", args = {MappedStatement.class,Object.class, RowBounds.class, ResultHandler.class} )}) public class MyInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { // Thread.sleep(5000); System.out.println("该插件被调用"); return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target,this); } @Override public void setProperties(Properties properties) { } }
在mybatis.conf.xml中的注册顺序
<plugins>
<plugin interceptor="com.belizer.mybatis.simple.UtilInterceptor"></plugin>
<plugin interceptor="com.belizer.mybatis.simple.MyInterceptor"></plugin>
</plugins>
执行顺序
该插件被调用
plugin output sql = select * from sys_user where id = ? , param=1