日期:2014-05-16  浏览次数:20471 次

spring 1.1.3 JDBC编程式事务管理探析(二):如何实现TransactionTemplate.execute的回调接口TransactionCal

?一、TransactionCallback接口

Object doInTransaction(TransactionStatus status)

TransactionTemplate已经搭好了事务框架,我们只需将多条SQL语句放在doInTransaction中执行就可以了。但是SQL语句通过什么方法来执行呢?

二、方法一:获取Connection来执行

获取Connection又有两种方法

1.从TransactionStatus中索得,因为TransactionStatus含有Transaction对象,后者保存了Connection的句柄

[Java] view plain copy
  1. private ? static ?Connection?getConnection(TransactionStatus?ts)?{??
  2. ??JdbcTransactionObjectSupport?transObj?=?(JdbcTransactionObjectSupport)((DefaultTransactionStatus)ts).getTransaction();??
  3. ??ConnectionHolder?holder?=?transObj.getConnectionHolder();??
  4. ??Connection?con?=?holder.getConnection();??
  5. ??return ?con;??
  6. }??

2.从TransactionSynchronizationManager的线程变量中获取

[Java] view plain copy
  1. private ?Connection?getConnection()?{??
  2. ??DataSourceTransactionManager?manager?=?(DataSourceTransactionManager)transactionTemplate.getTransactionManager();??
  3. ??DataSource?ds?=?manager.getDataSource();??
  4. ??return ?DataSourceUtils.getConnection(ds); // ??
  5. }??
这里贴出DataSourceUtils.getConnection(ds)的部分代码:
[Java] view plain copy
  1. public ? static ?Connection?getConnection(DataSource?dataSource,? boolean ?allowSynchronization)??
  2. ??throws ?CannotGetJdbcConnectionException?{??
  3. ??try ?{??
  4. ????return ?doGetConnection(dataSource,?allowSynchronization);??
  5. ??}??
  6. ??catch ?(SQLException?ex)?{??
  7. ????throw ? new ?CannotGetJdbcConnectionException( "Could?not?get?JDBC?connection" ,?ex);??
  8. ??}??
  9. }??
  10. ??
  11. protected ? static ?Connection?doGetConnection(DataSource?dataSource,? boolean ?allowSynchronization)??
  12. ??throws ?SQLException?{??
  13. ??...??
  14. ??ConnectionHolder?conHolder?=?(ConnectionHolder)?TransactionSynchronizationManager.getResource(dataSource);??
  15. ??if ?(conHolder?!=?