Mybatis之打开一个会话

本文深入解析MyBatis框架中Session的开启过程,详细介绍了如何通过SqlSessionFactory创建SqlSession,涉及配置读取、执行器与事务管理器的创建及会话的封装,为理解MyBatis核心机制提供清晰路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当解析完配置文件后会返回一个configuration作为sqlSessionFactory:

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

这里面包含了所有的mapper以及各种配置,下面我们就来看一下他是如何打开一个会话的:

SqlSession session = sqlSessionFactory.openSession();

这是我们的入口代码:

public SqlSession openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }

从configuration里面获得一个默认的执行器,作为参数为我们打开一个会话:

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);
      //返回一个包含执行器,是否开启了事务,以及配置信息的session
      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返回

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);
    }
    //判断是否开启了二级缓存,如果开启了封装执行器变成CachingExecutor
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

下一篇文章我们就要看是如何执行一个数据库操作的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值