Mybatis源码:openSession创建SqlSession

测试代码

    @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

image-20210114105827436

这里我们去看mybatis是怎么newExecutor的

image-20210114110432906

这里会根据ExecutorType判断出需要创建的Executor,默认是SIMPLE

然后如果cacheEnabled=true,又会new一个CachingExecutor,点进去,我们看看缓存的执行器是怎么创建的。

image-20210114110803468

这里CachingExecutor包装了Executor,并且实现了Executor接口,典型的装饰器模式。

继续,创建完CachingExecutor后,会调用interceptorChain的pluginAll方法,点击进入:

image-20210114111024502

这里会拿到所有的拦截器对象,并执行plugin拦截方法,拦截执行器CachingExecutor(拦截器重新包装Executor并返回)

最后返回的executor会作为参数传入到DefualtSqlSession的构造方法中,并包含configuration对象

image-20210114111313781

最后返回创建的sqlSession对象,包含了Configuration和Executor

原文地址:https://www.cnblogs.com/wwjj4811/p/14276248.html