Spring框架学习[Spring具体事务处理器的实现](四)
txObject.getConnectionHolder().getConnection() + "] rollback-only"); } txObject.setRollbackOnly(); } //操作完成之后清除操作 protected void doCleanupAfterCompletion(Object transaction) { DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction; //移除当前线程绑定的ConnectionHolder if (txObject.isNewConnectionHolder()) { TransactionSynchronizationManager.unbindResource(this.dataSource); } Connection con = txObject.getConnectionHolder().getConnection(); try { //如果事务对象保存了自动事务提交属性,则设置数据库连接的自动事务提交属性 if (txObject.isMustRestoreAutoCommit()) { con.setAutoCommit(true); } //事务结束后重置数据库连接 DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel()); } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } //如果事务对象中有新的ConnectionHolder if (txObject.isNewConnectionHolder()) { if (logger.isDebugEnabled()) { logger.debug("Releasing JDBC Connection [" + con + "] after transaction"); } //释放数据库连接 DataSourceUtils.releaseConnection(con, this.dataSource); } //清除事务对象的ConnectionHolder txObject.getConnectionHolder().clear(); } //数据源事务对象,内部类 private static class DataSourceTransactionObject extends JdbcTransactionObjectSupport { //是否有新的ConnectionHolder private boolean newConnectionHolder; //是否保存自动提交 private boolean mustRestoreAutoCommit; //设置ConnectionHolder public void setConnectionHolder(ConnectionHolder connectionHolder, boolean newConnectionHolder) { //为父类JdbcTransactionObjectSupport设置ConnectionHolder super.setConnectionHolder(connectionHolder); this.newConnectionHolder = newConnectionHolder; } public boolean isNewConnectionHolder() { return this.newConnectionHolder; } //调用父类JdbcTransactionObjectSupport的相关方法,查询收费存在事务 public boolean hasTransaction() { return (getConnectionHolder() != null && getConnectionHolder().isTransactionActive()); } //设置是否保存自动提交 public void setMustRestoreAutoCommit(boolean mustRestoreAutoCommit) { this.mustRestoreAutoCommit = mustRestoreAutoCommit; } public boolean isMustRestoreAutoCommit() { return this.mustRestoreAutoCommit; } //设置数据库连接在操作失败是,是否只回滚处理 public void setRollbackOnly() { getConnectionHolder().setRollbackOnly(); } public boolean isRollbackOnly() { return getConnectionHolder().isRollbackOnly(); } } }