测试代码
@Test
public void test01() throws IOException {
//1.根据xml配置文件(全局配置文件)创建一个SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
try {
EmployeeMapper employeeMapper= session.getMapper(EmployeeMapper.class);
Employee emp = employeeMapper.getEmpById(1);
System.out.println(emp);
session.clearCache();
Employee emp2 = employeeMapper.getEmpById(2);
System.out.println(emp2);
System.out.println(emp==emp2);
} finally {
session.close();
}
}
private SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
打上断点,openSession执行了openSessionFromDataSource
这里我们去看mybatis是怎么newExecutor的
这里会根据ExecutorType判断出需要创建的Executor,默认是SIMPLE
然后如果cacheEnabled=true,又会new一个CachingExecutor,点进去,我们看看缓存的执行器是怎么创建的。
这里CachingExecutor包装了Executor,并且实现了Executor接口,典型的装饰器模式。
继续,创建完CachingExecutor后,会调用interceptorChain的pluginAll方法,点击进入:
这里会拿到所有的拦截器对象,并执行plugin拦截方法,拦截执行器CachingExecutor(拦截器重新包装Executor并返回)
最后返回的executor会作为参数传入到DefualtSqlSession的构造方法中,并包含configuration对象
最后返回创建的sqlSession对象,包含了Configuration和Executor