【Mybatis源码分析】04-SqlSession的创建过程

作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO

联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬

学习必须往深处挖,挖的越深,基础越扎实!

阶段1、深入多线程

阶段2、深入多线程设计模式

阶段3、深入juc源码解析


阶段4、深入jdk其余源码解析


阶段5、深入jvm源码解析

码哥源码部分

码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】

码哥讲源码【炸雷啦!炸雷啦!黄光头他终于跑路啦!】

码哥讲源码-【jvm课程前置知识及c/c++调试环境搭建】

​​​​​​码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】

码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】

码哥讲源码【你水不是你的错,但是你胡说八道就是你不对了!】

码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】

终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!

打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】

SqlSession是我们操作数据库的主要客户端API,是由SqlSessionFactory的openSession方法所创建。openSession有多个重载方法,我们看一下:

    public interface SqlSessionFactory {
      SqlSession openSession();
      SqlSession openSession(boolean autoCommit);
      SqlSession openSession(Connection connection);
      SqlSession openSession(TransactionIsolationLevel level);
      SqlSession openSession(ExecutorType execType);
      SqlSession openSession(ExecutorType execType, boolean autoCommit);
      SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
      SqlSession openSession(ExecutorType execType, Connection connection);
      Configuration getConfiguration();
    }

看DefaultSqlSessionFactory的实现上面所有的openSession方法都是最终调用下面这个重载方法:

    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);
        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();
      }
    }

1.首先从configuration获取Environment对象,里面主要包含了DataSource和TransactionFactory对象

2.创建TransactionFactory创建Transaction

    public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
      return new JdbcTransaction(ds, level, autoCommit);
    }
    protected Connection connection;
    protected DataSource dataSource;
    protected TransactionIsolationLevel level;
    // MEMO: We are aware of the typo. See #941
    protected boolean autoCommmit;
    public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
      dataSource = ds;
      level = desiredLevel;
      autoCommmit = desiredAutoCommit;
    }

JdbcTransaction主要维护了一个默认autoCommit为false的Connection对象,对事物的提交,回滚,关闭等都是接见通过Connection完成的。

    protected void openConnection() throws SQLException {
      if (log.isDebugEnabled()) {
        log.debug("Opening JDBC Connection");
      }
      connection = dataSource.getConnection();
      if (level != null) {
        connection.setTransactionIsolation(level.getLevel());
      }
      setDesiredAutoCommit(autoCommmit);//默认为false
    }
    public void rollback() throws SQLException {
      if (connection != null && !connection.getAutoCommit()) {
        if (log.isDebugEnabled()) {
          log.debug("Rolling back JDBC Connection [" + connection + "]");
        }
        connection.rollback();
      }
    }
    public void close() throws SQLException {
      if (connection != null) {
        resetAutoCommit();
        if (log.isDebugEnabled()) {
          log.debug("Closing JDBC Connection [" + connection + "]");
        }
        connection.close();
      }
    }
    public void commit() throws SQLException {
      if (connection != null && !connection.getAutoCommit()) {
        if (log.isDebugEnabled()) {
          log.debug("Committing JDBC Connection [" + connection + "]");
        }
        connection.commit();
      }
    }

3.从configuration获取Executor。executor包含了刚刚创建的Transaction,所以Transaction关联了Connection和Executor,如果为指定executorType则使用默认的SimpleExecutor,如果开启了二级缓存(默认开启),则CachingExecutor会包装SimpleExecutor,然后依次调用拦截器的plugin方法返回一个被代理过的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);
      }
      if (cacheEnabled) {
        executor = new CachingExecutor(executor);
      }
      executor = (Executor) interceptorChain.pluginAll(executor);
      return executor;
    }

4.构造DefaultSqlSession对象

    new DefaultSqlSession(configuration, executor, autoCommit)

5.如果上述一步出现异常,则会调用Transaction的close方法,间接调用DataSource(PooledDataSource)的方法回收或释放连接。

    private void closeTransaction(Transaction tx) {
      if (tx != null) {
        try {
          tx.close();
        } catch (SQLException ignore) {
          // Intentionally ignore. Prefer previous error.
        }
      }
    }

以上创建DefaultSqlSession的过程主要就是为了得到Configuration和一个Executor。下篇文章分析一下DefaultSqlSession的具体实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值