源码解析(三):MyBatis如何选择数据源

本文探讨了在自定义数据源的场景下,MyBatis如何使用数据源建立连接的过程,详细解析了Mybatis调用数据源的时序图,并着重介绍了主流程,包括SimpleExecutor、SpringManagedTransaction及DataSourceUtils的角色和作用。

简介

当我们自定义数据源 DynamicDataSource, 时, MyBatis是如何使用这个数据源, 并且建立连接的

Mybatis调用数据源时序图

在这里插入图片描述

绿色部分为我们业务实现代码。

主流程

在执行器 Executor中生成 Statement, 首先建立连接, 事务管理器中生成连接, 通过事务管理器检查是否为事务,

SimpleExecutor

在这里插入图片描述

生成

Statement

private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
  Statement stmt;
  //获取连接
  Connection connection = getConnection(statementLog);
  stmt = handler.prepare(connection, transaction.getTimeout());
  handler.parameterize(stmt);
  return stmt;
}

SpringManagedTransaction

在这里插入图片描述

private void openConnection() throws SQLException {
  //获取连接
  this.connection = DataSourceUtils.getConnection(this.dataSource);
  //是否自动提交
  this.autoCommit = this.connection.getAutoCommit();
  //是否为事务
  this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource);

DataSourceUtils

调用dataSource 的连接

public static Connection doGetConnection(DataSource dataSource) throws SQLException {
   Assert.notNull(dataSource, "No DataSource specified");
 
   //是否为事务,线程绑定
   ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
   if (conHolder != null && (conHolder.hasConnection() || conHolder.isSynchronizedWithTransaction())) {
      conHolder.requested();
      if (!conHolder.hasConnection()) {
         logger.debug("Fetching resumed JDBC Connection from DataSource");
         conHolder.setConnection(dataSource.getConnection());
      }
      return conHolder.getConnection();
   }
   // Else we either got no holder or an empty thread-bound holder here.
 
   //调用 datasource 的 getConnection()
   logger.debug("Fetching JDBC Connection from DataSource");
   Connection con = dataSource.getConnection();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值