深入MyBatis-运行原理-SqlSession的初始化

流程图

在这里插入图片描述

  1. DefaultSqlSessionFactory调用opensseion方法
  2. opensession方法下,调用openSessionFromDataSource方法
  3. openSessionFromDataSource方法下获取configuration信息,并创建事务,调用newExecutor方法,生成Executor,并返回
  4. 拦截器类对Executor进行加强后返回Executor
  5. 返回DefaultSqlSession给DefaultSqlSessionFactory
剖析源码
1.DefaultSqlSessionFactory调用openSession方法
sqlSession = sqlSessionFactory.openSession();
2.openSession方法下调用openSessionFromDataSource方法
public SqlSession openSession() {
	//调用此方法会返回SqlSession
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }
3.openSessionFromDataSource下获取配置信息,生成事务和Executor并返回DefaultSqlSession
 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);
      //生成Executor
      final Executor executor = configuration.newExecutor(tx, execType);
      //传入配置信息和Executor,创建SqlSession
      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();
    }
  }
5.Executor
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    //判断Executor类型
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      //默认Execuotr类型为SIMPLE
      executor = new SimpleExecutor(this, transaction);
    }
    //如果开启了二级缓存,则生成CachingExecutor
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    //调用拦截器链加强Executor对象,插件在此发挥作用
    executor = (Executor) interceptorChain.pluginAll(executor);
    //返回Executor
    return executor;
  }
小结

调用DefaultSqlSessionFactory下的openSession方法可以返回SqlSession。在此之前,需要传入Configuration,创建Executor作为参数传入,生成Executor的条件需要事务管理和Executor类型。完成信息的配置后,返回SqlSession给调用者。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值