Mybatis中Mapper接口注册到Spring容器中的Bean是通过MapperProxyFactory
类中的动态代理实现。而Mapper中具体接口方法对应MapperMethod
实例,MapperMethod
中执行又执行到了SqlSessionTemplate
,SqlSessionTemplate
中委托给自己的一个SqlSession动态代理类,SqlSession实例是由sessionFactory的指定执行器的openSession方法创建。
这里开始从代码查看。
DefaultSqlSessionFactory
是SqlSessionFactory
的实现
public class DefaultSqlSessionFactory implements SqlSessionFactory {
/* ... */
@Override
public SqlSession openSession(ExecutorType execType) {
// 默认不自动提交
return openSessionFromDataSource(execType, null, false);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
// 事务管理
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
// 创建执行器,这个步骤会关联到拦截器,进入查看
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
}
查看创建执行器方法
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
// 如果执行器类型为null,选择默认执行器,默认执行器就是 SIMPLE类型
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
// 根据执行器类型创建对应的执行器实例
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
// 过滤器链,底层是一个过滤器的List。过滤器链的加入这里是在执行器上加入拦截器,这里拦截器不仅对执行器
// 过滤器链在SpringBoot中是通过MybatisAutoConfiguration中获取注册到Spring容器中的bean集合
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
// 这里不仅拦截器对执行器进行配置,对ParameterHandler、 ResultSetHandler、StatementHandler都进行了配置,而这四个是SqlSession的重要对象
// 处理SQL参数
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
// 处理封装查询结果集ResultSet
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
// 处理Statement对象,即对执行数据库操作。
// 这里默认是PrepareStatement,类型包括Statement、SimpleStatement和CallableStatement,可以在mapper中指定具体的类型
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
查看拦截器如何进行设置
public class InterceptorChain {
private final List<Interceptor> interceptors = new ArrayList<>();
/* ... */
// 遍历拦截器集合,把传入的对象层层执行赋值,这点开始看还是比较奇怪的
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
/* ... */
}
继续看拦截器中的方法,拦截器这里有三个方法,两个默认方法,实现拦截器可以只实现intercept
方法。
public interface Interceptor {
// Invocation 是一个实体类
Object intercept(Invocation invocation) throws Throwable;
// 直接调用Plugin.wrap方法
default Object plugin(Object target) {
return Plugin.wrap(target, this);
}
default void setProperties(Properties properties) {
// NOP
}
查看Plugin的wrap方法
// 1、先看到这个方法返回对象就明白了,为什么拦截器链执行设置对象要层层赋值,原来是通过返回动态代理对象或原对象,进行了层层代理!
// 2、但是如何知道对哪些方法进行代理,怎么进行代理。具体查看代码
public static Object wrap(Object target, Interceptor interceptor) {
// 代码1
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
// 代码2
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
// 代码3
new Plugin(target, interceptor, signatureMap));
}
return target;
}
下面根据分页拦截器的代理理解查看。
先查看代码1 getSignatureMap
方法,方法参数为拦截器对象
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
// 拦截器上面必须要有Intercepts 注解,否则报错
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
// issue #251
if (interceptsAnnotation == null) {
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
// 得到 Signature注解 ,Signature 包含class对象,方法名称和参数对应的类的数组
Signature[] sigs = interceptsAnnotation.value();
// 存储map。key为class对象,value对方法集合
Map<Class<?>, Set<Method>> signatureMap = new HashMap<>();
for (Signature sig : sigs) {
Set<Method> methods = signatureMap.computeIfAbsent(sig.type(), k -> new HashSet<>());
try {
// 这里根据Signature注解中的类对象,通过方法和参数获取具体的method,添加到method集合中
// 所以这里Signature的作用就是根据指定值获取具体的方法对象
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
}
}
return signatureMap;
}
如分页拦截器插件
获取到拦截上设置的注解信息后,接着看代码2 getAllInterfaces
方法,了解这些值的作用。
// 第一个参数表示的是拦截器要设置的对象,如上面的新建执行器,对象是 SimpleExecutor 对应的类对象
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<>();
// 如果类对象不为null,继续循环
while (type != null) {
// 当前的类的接口集合,如果Signature注解的信息存储中包含了这个接口,就添加到集合中
// 所以Signature注解中的类对象表示要是接口的类对象,方法是接口中的方法
for (Class<?> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
// 当前的类对象的超类赋值到当前的类对象
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[0]);
}
// 所以这个方法的作用是获取拦截器所设置的对象所实现的接口定义在了Signature注解中的集合,获取动态代理对象需要代理实现的接口
如果有对象所实现的接口定义在了Signature注解中,定义了要就执行动态代理了。查看代码3。Plugin
类本身实现了InvocationHandler
,查看实现的invoke
方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 得到当前方法的接口,从signatureMap获取这个接口要代理的方法集合
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
// 如果当前接口有需要代理的方法,而且要执行的方法是需要代理的方法,调用拦截器的 intercept方法,实现拦截器必须重写的就是这个方法。方法参数相当于一个实体类,封装了代理对象,方法实例和方法参数
if (methods != null && methods.contains(method)) {
return interceptor.intercept(new Invocation(target, method, args));
}
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
总结:
拦截器对SqlSession的四大对象Executor、ParameterHandler、 ResultSetHandler和StatementHandler都会执行配置,通过执行层层代理,可以实现执行自定义的处理。
Mybatis拦截器的使用:
1、需要实现org.apache.ibatis.plugin.Interceptor
类,intercept
方法是具体的自定义处理。参数Invocation相当于一个实体类。
// 这个对应Signature注解中的信息
public class Invocation {
// 对应 type,是type表示接口的具体实现类,被代理类
private final Object target;
// 对应 method,代理的方法
private final Method method;
// 对应 args,代理方法的参数
private final Object[] args;
// getter
// setter
}
2、拦截器类上必须有@Intercepts
注解,value值是所拦截的具体方法,抽象成@Signature
表示
3、@Signature
注解的属性值设定
public @interface Signature {
// 表示要拦截的接口,只能是下面四种
// Executor:拦截执行器的方法。比如分页的拦截器插件。
// ParameterHandler:拦截参数的处理。
// ResultHandler:拦截结果集的处理。
// StatementHandler:拦截Sql语法构建的处理。
Class<?> type();
// 上面四种类型中的方法
String method();
// 方法的参数,顺序也必须与方法参数顺序一致
Class<?>[] args();
}