Mybatis执行流程浅析
阅读原文时间:2023年07月12日阅读:1

从三个主要的对象SqlSessionFactoryBuilder->SqlSessionFactory->SqlSession说起

            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  1. 读取全局配置文件

    inputStream = Resources.getResourceAsStream(resource);

  2. 创建了一个SqlSessionFactoryBuilder对象

  3. 调用.getResourceAsStream(resource)方法,完成相关配置并创建SqlSessionFactory对象

    //点击进入可知对XML文件进行了解析,从而获得了XMLConfiguration,且该对象继承自Configuration对象.进入下一步的build查看
    public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    SqlSessionFactory var5;
    try {
    XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
    var5 = this.build(parser.parse());
    } catch (Exception var14) {
    throw ExceptionFactory.wrapException("Error building SqlSession.", var14);
    } finally {
    ErrorContext.instance().reset();

            try {
                inputStream.close();
            } catch (IOException var13) {
            }
    }
    
    return var5;
    }

    //加Configuration对象加载给SqlSessionFactory对象,完成了SqlSessionFactory的创建
    public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
    }

  4. 调用SqlSessionFactory对象的openSession方法完SqlSession对象的实例化

    //往下:可以看出是先继承了Configuration中的Environment,完成了transaction相关的操作,继而产生executor,最后才完成了SqlSession的实例化,能力有限,这里就不深究了
    private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;

        DefaultSqlSession var8;
        try {
            Environment environment = this.configuration.getEnvironment();
            TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);
            tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
            Executor executor = this.configuration.newExecutor(tx, execType);
            var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
        } catch (Exception var12) {
            this.closeTransaction(tx);
            throw ExceptionFactory.wrapException("Error opening session.  Cause: " + var12, var12);
        } finally {
            ErrorContext.instance().reset();
        }
    return var8;
    }
  5. CURD的执行(产生错误就回滚)

  6. 检测是否执行(产生错误就回滚)

  7. 提交

    8.关闭