简介
当我们自定义数据源 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();
本文探讨了在自定义数据源的场景下,MyBatis如何使用数据源建立连接的过程,详细解析了Mybatis调用数据源的时序图,并着重介绍了主流程,包括SimpleExecutor、SpringManagedTransaction及DataSourceUtils的角色和作用。

2069

被折叠的 条评论
为什么被折叠?



