接上文: mybatis - 初始化
接上文,既然拿到了SqlSessionFactory,下一步就是在方法中用来获取SqlSession了:
// 获取SqlSession,线程不可全
SqlSession sqlSession = initAndReturnSqlSessionFactory().openSession();
// 通过SqlSession获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
那么就看看这个关键的openSession()方法,上文已知SqlSessionFactory的唯一默认实现是DefaultSqlSessionFactory,那么,就看看 这个过程中做了些什么,用代码加注释说话:
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), 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) {
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);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
加入代理链(这个设计很good,逻辑有点绕,我这简单的头脑需要花些时间才明白做了些什么): 实际,每个代理对象都代理着前一个代理对象,前一个代理对象做为target加入到新的代理实现中
// 依次创建代理对象,返回一个包含前一个代理对象的代理对象,这样把target和所以拦截器串起来一个调用链
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
重新梳理下:
<p> 创建 </p>
// 传入上一个代理对象,生成并返回新的代理对象
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
插件包装方法
public static Object wrap(Object target, Interceptor interceptor) {
// 要拦截的类与其方法的映射集合
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
// 拦截器的类型
Class<?> type = target.getClass();
// 该拦截器实现的所有接口
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
// 生成代理对象,原有的对象target将被做为旧的实现被新的代理对象调用
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
/**
* 这个方法解析拦截器的注解,生成要拦截的类与其方法的映射集合
*/
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());
}
// 注解的value,返回Signature(签名)数组
Signature[] sigs = interceptsAnnotation.value();
// 定义类及方法集合的映射表
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
for (Signature sig : sigs) {
// 先从映射表中获取方法集合,以类为Key, 若为空则填充
Set<Method> methods = signatureMap.get(sig.type());
if (methods == null) {
methods = new HashSet<Method>();
signatureMap.put(sig.type(), methods);
}
try {
// 反射包中的方法,从Class对象中获取Method对象,传入方法名和参数类型
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;
}
// 对type及期层层遍历所有接口,如果有包含在拦截列表中的,就加入到接口列表最后返回,返回的是该类型所实现的所有被拦截的接口(特么的不就是找Interceptor接口吗?哦,其实还有Executor、ResultHandler、ParameterHandler、StatementHandler,这些都创建时都调用了InterceptorChain的pluginAll方法)
private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
Set<Class<?>> interfaces = new HashSet<Class<?>>();
while (type != null) {
for (Class<?> c : type.getInterfaces()) {
if (signatureMap.containsKey(c)) {
interfaces.add(c);
}
}
type = type.getSuperclass();
}
return interfaces.toArray(new Class<?>[interfaces.size()]);
}
呼,好多,总结下:
- 用TransactionFactory 创建一个Transaction ;
- 创建一个执行器Executor;
- 创建一个默认的SqlSession: new DefaultSqlSession(configuration, executor, autoCommit);
创建 执行器的过程中又发生了神马:
- 确认执行器类型;
- 按类型new一个相应的执行器实现,传入事务对象;
- 判断是否开启缓存(),如果开启,使用刚创建的执行器再创建一个缓存执行器;
- 最后,调用interceptorChain.pluginAll(executor)生成新的执行器代理实现,该实现层层代理了所有拦截器;