spring 1.1.3 JDBC编程式事务管理探析(二):如何实现TransactionTemplate.execute的回调接口TransactionCal
?一、TransactionCallback接口
Object doInTransaction(TransactionStatus status)
TransactionTemplate已经搭好了事务框架,我们只需将多条SQL语句放在doInTransaction中执行就可以了。但是SQL语句通过什么方法来执行呢?
二、方法一:获取Connection来执行
获取Connection又有两种方法
1.从TransactionStatus中索得,因为TransactionStatus含有Transaction对象,后者保存了Connection的句柄
-
private
?
static
?Connection?getConnection(TransactionStatus?ts)?{??
-
??JdbcTransactionObjectSupport?transObj?=?(JdbcTransactionObjectSupport)((DefaultTransactionStatus)ts).getTransaction();??
-
??ConnectionHolder?holder?=?transObj.getConnectionHolder();??
-
??Connection?con?=?holder.getConnection();??
-
??return
?con;??
-
}??
2.从TransactionSynchronizationManager的线程变量中获取
-
private
?Connection?getConnection()?{??
-
??DataSourceTransactionManager?manager?=?(DataSourceTransactionManager)transactionTemplate.getTransactionManager();??
-
??DataSource?ds?=?manager.getDataSource();??
-
??return
?DataSourceUtils.getConnection(ds);
??
-
}??
这里贴出DataSourceUtils.getConnection(ds)的部分代码:
-
public
?
static
?Connection?getConnection(DataSource?dataSource,?
boolean
?allowSynchronization)??
-
??throws
?CannotGetJdbcConnectionException?{??
-
??try
?{??
-
????return
?doGetConnection(dataSource,?allowSynchronization);??
-
??}??
-
??catch
?(SQLException?ex)?{??
-
????throw
?
new
?CannotGetJdbcConnectionException(
"Could?not?get?JDBC?connection"
,?ex);??
-
??}??
-
}??
-
??
-
protected
?
static
?Connection?doGetConnection(DataSource?dataSource,?
boolean
?allowSynchronization)??
-
??throws
?SQLException?{??
-
??...??
-
??ConnectionHolder?conHolder?=?(ConnectionHolder)?TransactionSynchronizationManager.getResource(dataSource);??
-
??if
?(conHolder?!=?