mybatis0090-SqlSessionFactory创建SqlSession

    xiaoxiao2025-01-20  9

    文章目录

    1. 创建SqlSession2. DefaultSqlSessionFactory的openSessionFromDataSource3. 执行流程

    1. 创建SqlSession

    SqlSession sqlSession = sqlSessionFactory.openSession();

    2. DefaultSqlSessionFactory的openSessionFromDataSource

    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(); } }

    创建SqlSession的过程,其实是对jdbc的Connection的一次再封装,Connection–>Statement–>Executor–>SqlSeesion Executor有三种类型:SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements); BATCH 执行器将重用语句并执行批量更新。configuration.newExecutor(tx, execType)会根据execType创建出其中一种执行器(默认是ExecutorType.SIMPLE),如下:

    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; }

    最后,将执行器和配置对象封装到SqlSession中返回,所以对于使用mybatis把SqlSession当作Connection来使用即可。

    3. 执行流程

    最新回复(0)