1.创建xxxMapper 接口的MapperFactoryBean对象
// 入参 RootBeanDefinition对象,其属性beanClass=MapperFactoryBean.class
// MapperFactoryBean类的接口为常见的FactoryBean
Object doCreateBean()->{
// 实例化对象,创建MapperFactoryBean对象,其属性
// Class mapperInterface= xxxMapper.class
// SqlSession sqlSession=null;
//
Object bean = instanceWrapper.getWrappedInstance();
// 调用父类SqlSessionDaoSupport.setSqlSessionTemplate(...)
// 初始化对象MapperFactoryBean的属性
// SqlSession sqlSession= SqlSessionTemplate对象
// 其属性sqlSessionFactory,executorType,sqlSessionProxy=DefaultSqlSession.class
// ,exceptionTranslator。
this.populateBean(beanName, mbd, instanceWrapper);
//MapperFactoryBean对象的父类DaoSupport类实现InitializingBean
// initializeBean(...)->{
// invokeInitMethods(...)->{
// // 调用checkDaoConfig()
// // 从SqlSessionTemplate.DefaultSqlSessionFactory中拿到Configuration
// // 其对象属性有Environment的对象,mappedStatements,caches 二级缓存,
// // 属性MapperRegistry mapperRegistry对象的属性knownMappers
// // knownMappers为HashMap,key=xxxMapper.class
// // value=MapperProxyFactroy对象
// // 该方法作用1.knownMappers put MapperProxyFactory(key)对象
// // 2.MapperAnnotationBuilder对象.parse() 该方法一个
// // 作用是有@CacheNamespace注解时,则向configuration.caches添加
// // SynchronizedCache对象 ,之后configuration.mappedStatements添加
// // MappedStatement对象其属性
// // id=xxxMapper.xxx,cache=configuration.caches中的一个
// MapperFactoryBean对象.afterPropertiesSet()
// }
// }
initializeBean(...);
}
2. 通过@Autowired注解,创建xxxMapper 接口的代理对象,自动导入到其类的属性上
// 通过@Autowired注解,创建xxxMapper 接口的代理对象,自动导入到其类的属性上
T doGetBean(...)->{
Object sharedInstance = this.getSingleton(...);
// sharedInstance 为xxxMapper.class的MapperFactoryBean对象
bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd)->{
//如果不是正在创建的对象,beanName不是以&开头,sharedInstance,sharedInstance是
// FactoryBean时,则调用getObjectFromFactoryBean()方法
getObjectFromFactoryBean()->{
//从factoryBeanObjectCache中获取MapperProxy代理对象
Object object = this.factoryBeanObjectCache.get(beanName);
//object == null
object = this.doGetObjectFromFactoryBean(...)->{
//根据xxxMapper.class从MapperFactoryBean.DefaultSqlSessionFactory.
// Configuration.MapperRegistry.knownMappers
// 得到mapperProxyFactory对象
MapperProxyFactory<T> mapperProxyFactory =
(MapperProxyFactory)this.knownMappers.get(type);
// 创建代理对象
return mapperProxyFactory.newInstance(sqlSession)->{
// InvocationHandler h= new MapperProxy();
// MapperProxy其类属性sqlSessionTemplate,mapperInterface,
// methodCache
return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(),
new Class[]{this.mapperInterface}, mapperProxy);
};
// 将MapperProxy代理对象放入到factoryBeanObjectCache
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return bean;
}
3. 调用xxxMapper的代理对象时,被JdkDynamicAopProxy对象拦截。
//JdkDynamicAopProxy的adviesd= ProxyFactory对象
// 其属性aopProxyFactory= DefaultAopProxyFactory
// targetSource 为代理对象
// advisors 为PersistenceExceptionTranslationAdvisor.class
// advice为PersistenceExceptionTranslationInterceptor
// new ReflectiveMethodInvocation对象MethodInvocation invocation
retVal = invocation.proceed()->{
// 调用PersistenceExceptionTranslationInterceptor.invoke()方法
// 捕获RuntimeException异常做处理
try{
mapperProxy.invoke()->{
// 从methodCache中获取mapperMethod对象,如果为null,创建。然后put
// methodCache中
// MapperMethod类MapperMethod.SqlCommand command
// MapperMethod.MethodSignature method
mapperMethod.execute(this.sqlSession, args)->{
//判断SqlCommandType类,如果为SELECT
result = sqlSession.selectOne(...)->{
//获取DefaultSqlSession其属性Configuration configuration;
// Executor executor=为CachingExecutor类代理对象h
// 为Plugin,其属性PageInterceptor和target
// 为CachingExecutor其属性delegate为SimpleExecutor
// TransactionalCacheManager tcm 事务缓存
// tcm的属性Map<Cache, TransactionalCache> transactionalCaches中
// map的key为SynchronizedCache(与每一个xxxmapper)
// value为TransactionalCache其属性delegate为key对象
// 其属性entriesToAddOnCommit中key为CacheKey和
// value为对象结果
SqlSession sqlSession = getSqlSession(...)
try {
Object result = method.invoke(sqlSession, args)->{
//MappedStatement属性configuration,statementType
// ='PREPARED'(预处理,预编译,获取数据),sqlSource中
// sql为select语句,parameterMap/resultMaps,cache
// xxxMapper对应二级缓存
// xxxMapper.方法的信息
MappedStatement ms =
this.configuration.getMappedStatement(...);
//其中executor为代理对象,执行拦截器PageInterceptor
this.executor.query(...) ->{
PageInterceptor.intercept()->{
// xxxMapper.方法唯一标识
cacheKey = executor.createCacheKey(ms, parameter,
rowBounds, boundSql);
cachingExecutor.query(...,cacheKey...)->{
//MappedStatement ms中的cache为null,
// 未开启二级缓存
simpleExecutor.query()->{
//先取结果simpleExecutor.localCache
// 为一级缓存
// 如果为null,从数据库中查
PreparedStatement ps;ps.execute();
//将结果simpleExecutor.localCache存入
// PerpetualCache id=“LocalCache”,
// cache为HashMap,key=CacheKey|value为结果
}
//MappedStatement ms中的cache为null,UseCache
// =true 开启二级缓存
// 1.向tcm中添加cache(可能包含结果)和CacheKey
// 2.如果从tcm取不到结果,则simpleExecutor
// 查结果,存到localCache
// 3.将结果存到tcm中的cache中
}
}
}
}
// 在processCommit()->triggerBeforeCommit()->{
// // 清除一级缓存
// // 将每个TransactionalCache的entriesToAddOnCommit结果put
// // 到 cache中()存到二级缓存,之后提交。下次使用二级缓存
// CachingExecutor.TransactionalCacheManager(tcm).commit(..)
// }
// sqlSession.commit(true);
return result;
}catch (Throwable t){
//sqlSession != null,则执行
closeSqlSession(...);
}finally {
closeSqlSession(...);
}
};
}
}
}catch(RuntimeException var4){
...
}
}
一级缓存和二级缓存
//一级缓存,BaseExecutor的实现类SimpleExecutor
class SimpleExecutor {
// PerpetualCache属性Map<Object, Object> cache为key=CacheKey,value=结果
// 属性 String id = com.xx.xxxMapper
protected PerpetualCache localCache;
}
// 二级缓存Configuration.caches中map的一个key(com.xx.xxxMapper)和
// value(1.SynchronizedCache)
// Configuration.mappedStatements中map的一个key(com.xx.xxxMapper.xx)和valve
// (MappedStatement.cache=2.SynchronizedCache对象)
// TransactionalCacheManager.transactionalCaches中map的一个
// key(3.SynchronizedCache)
// value(TransactionCache.delegate(4.SynchronizedCache))
// 上面四个SynchronizedCache是相同对象
// 对该缓存操作都是同步操作
public class SynchronizedCache {
// loggingCache hits,requests,delegate 查看一次,hits命中加1,requests加1
// SerializedCache delegate put序列化和get反序列化方法
// LruCache keyMap,eldestKey,delegate
// PerpetualCache id,cache
private Cache delegate ;
}
//1. 创建SqlSessionFactoryBean,其属性
// DataSource dataSource
// SqlSessionFactoryBuilder sqlSessionFactoryBuilder
// SpringManagedTransactionFactory transactionFactory
SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
//2. 根据配置,创建DefaultSqlSessionFactory对象
SqlSessionFactory sqlSessionFactoryBuilder.build(Configuration config)->{
return new DefaultSqlSessionFactory(config);
}
//3 通过MybatisAutoConfiguration自动配置类
// 根据DefaultSqlSessionFactory对象和默认ExecutorType.SIMPLE(REUSE|BATCH)
// 创建SqlSessionTemplate对象
SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(DefaultSqlSessionFactory)