Mybatis的源码解析(二):SqlSession

Mybatis的流程:

在这里插入图片描述

2.获取SqlSession对象

  • 从配置文件中取出Exceutor(执行器),调用openSessionFromDataSource()
    在这里插入图片描述
  • 新建的执行器的类型默认为:SIMPLE
    在这里插入图片描述
  • 执行器的类型有三种:
    在这里插入图片描述
  • 注意:
    在这里插入图片描述
	executor = (Executor) interceptorChain.pluginAll(executor);

对Executor进行拦截增强 ,这里使用的设计模式为装饰者模式

  • 然后返回:DefaultSqlSession(configuratioin,executor,事务问题)
    Executor执行 configuratioin中的增删改在这里插入图片描述

总结:得到SqlSession的过程

  • 首先SqlSessionFactory调用openSession()
    SqlSession session = sessionFactory.openSession();
    
  • 然后openSession() 调用 openSessionFromDataSource()
     @Override
    public SqlSession openSession() {
      return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
    }
    
  • 返回DefaultSqlSession对象,注意DefaultSqlSession包括: (configuration,executor,事务)
    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);
      //创建一个新的执行器,类型为execType
      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();
    }
    }
    
发布了47 篇原创文章 · 获赞 34 · 访问量 8873

猜你喜欢

转载自blog.csdn.net/weixin_42893085/article/details/105181855