Mybatis源码分析-openSession()源码分析


一、openSession()作用概括

  • 创建事务
  • 创建Excutor
  • 把创建好得事务和Excutor交给DefaultSqlSession
  • 封装了select | insert | update | delete方法

二、openSession()源码分析

1、用法中

用法中我们通过sqlSessionFactory.build()方法创建好sqlSessionFactory然后通过

 SqlSession sqlSession = sqlSessionFactory.openSession();

获取我们得sqlSession那么我们接下来去看源码

2、openSession()

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

可以看到openSession中调用了openSessionFromDataSource方法 我们继续追踪源码

3、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);
      //获取Executor 
      final Executor executor = configuration.newExecutor(tx, execType);
      //返回DefaultSqlSession
      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();
    }
  }

4、获取Executor 执行器

1.执行器类型

  1. SimpleExecutor:默认的Executor,每个SQL执行时候都会创建新的Statement
  2. ReuseExecutor:相同的SQL会重复使用Statement
  3. BatchExecutor:用于批处理的Executor
  4. CachingExecutor:可缓存数据的Executor,用代理模式包装了其他类型的Executor
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);
    }
    //默认是true 默认先创建简单的Executor 然后再创建CachingExecutor
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    //最后把创建好的执行器返回
    return executor;
  }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值