}
public static Connection doGetConnection(DataSource dataSource, boolean distribute) throws SQLException {
CommonUtils.assertNotNull(dataSource, "No DataSource specified");
JdbcTransactionContext txObject = (JdbcTransactionContext) TransactionContextHolder.getContext();
if (txObject == null) {// 不支持事务
return dataSource.getConnection();
}
boolean shouldAddCount = false;
Connection con = null;
ConnectionHolder conHolder = txObject.getConnectionHolder();
if (conHolder != null && conHolder.getCurrentConnection() != null) {// 已经存在事务
// 判断是否可以使用上次的connection
if (dataSource.equals(txObject.getTxDataSource())) {// 只对同一数据源进行事务处理
con = conHolder.getCurrentConnection();
shouldAddCount = true;
} else {
con = dataSource.getConnection();
}
} else { // 第一次开始事务
JdbcTransactionManager txManager = (JdbcTransactionManager) txObject.getTxManager();
if (distribute) {// 分布式数据源,只在第一此写操作时启动事务
if (needBeginTransaction()) {
beginNewTransaction(dataSource, txObject);
con = txObject.getConnectionHolder().getCurrentConnection();
shouldAddCount = true;
} else {// 创建独立于事务之外的connection
con = dataSource.getConnection();
}
} else if (txManager.isLazyBegin()) {// 仅懒启动式事务,第一次启动事务
beginNewTransaction(dataSource, txObject);
con = txObject.getConnectionHolder().getCurrentConnection();
shouldAddCount = true;
} else {
throw new TransactionException("not lazyBegin transaction bu no currentConnection exist");
}
conHolder = txObject.getConnectionHolder(); // 重新获取ConnectionHolder
}
if (shouldAddCount) {
conHolder.addCounter();
}