SSM-MyBatis-06:Mybatis中openSession到底做了什么

时间:2021-02-18 12:59:39
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------

1.找SqlSesionFactory实现类
  Ctrl+H:DefaultSqlSessionFactory:
  Ctrl+F :openSession()方法
  原型如下:
  public SqlSession openSession() {
    return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, false);
  }

2.查看openSessionFromDataSource方法的实现
  private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null; 定义事务对象
    很明显:SqlSession实现类
    DefaultSqlSession var8;
    try {
      //读取 MyBatis-Config.xml 形成 Environment对象
      Environment e = this.configuration.getEnvironment();
      //通过环境e作为入参,获取到事务工厂
      TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(e);
      //创建事务对象
      tx = transactionFactory.newTransaction(e.getDataSource(), level, autoCommit);
      //MyBatis执行器 Executor 执行器
      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;
  }

3.查看DefaultSqlSession方法的实现
  private Configuration configuration; //配置
  private Executor executor; //执行器
  private boolean autoCommit; //事务自动提交的
  private boolean dirty; //脏 Java 内存中泛型数据 和底层DB数据 不一样 干净的(Java内存===DB Data 一致的)
  private List<Cursor<?>> cursorList; 游标 让记录前进的一个工具

  public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
    this.configuration = configuration;
    this.executor = executor;
    this.dirty = false; //干净的
    this.autoCommit = autoCommit;
  }

结论:通过以上3个步骤,我们不难发现,openSession 就是对DefaultSqlSession类中的成员变量赋值