1 16 17 package org.springframework.transaction.support; 18 19 import org.apache.commons.logging.Log; 20 import org.apache.commons.logging.LogFactory; 21 22 import org.springframework.beans.factory.InitializingBean; 23 import org.springframework.transaction.PlatformTransactionManager; 24 import org.springframework.transaction.TransactionDefinition; 25 import org.springframework.transaction.TransactionException; 26 import org.springframework.transaction.TransactionStatus; 27 28 59 public class TransactionTemplate extends DefaultTransactionDefinition implements InitializingBean { 60 61 62 protected final Log logger = LogFactory.getLog(getClass()); 63 64 private PlatformTransactionManager transactionManager = null; 65 66 67 73 public TransactionTemplate() { 74 } 75 76 80 public TransactionTemplate(PlatformTransactionManager transactionManager) { 81 this.transactionManager = transactionManager; 82 } 83 84 90 public TransactionTemplate(PlatformTransactionManager transactionManager, TransactionDefinition transactionDefinition) { 91 super(transactionDefinition); 92 this.transactionManager = transactionManager; 93 } 94 95 98 public void setTransactionManager(PlatformTransactionManager transactionManager) { 99 this.transactionManager = transactionManager; 100 } 101 102 105 public PlatformTransactionManager getTransactionManager() { 106 return transactionManager; 107 } 108 109 public void afterPropertiesSet() { 110 if (this.transactionManager == null) { 111 throw new IllegalArgumentException ("transactionManager is required"); 112 } 113 } 114 115 116 126 public Object execute(TransactionCallback action) throws TransactionException { 127 if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) { 128 return ((CallbackPreferringPlatformTransactionManager) this.transactionManager).execute(this, action); 129 } 130 else { 131 TransactionStatus status = this.transactionManager.getTransaction(this); 132 Object result = null; 133 try { 134 result = action.doInTransaction(status); 135 } 136 catch (RuntimeException ex) { 137 rollbackOnException(status, ex); 139 throw ex; 140 } 141 catch (Error err) { 142 rollbackOnException(status, err); 144 throw err; 145 } 146 this.transactionManager.commit(status); 147 return result; 148 } 149 } 150 151 157 private void rollbackOnException(TransactionStatus status, Throwable ex) throws TransactionException { 158 logger.debug("Initiating transaction rollback on application exception", ex); 159 try { 160 this.transactionManager.rollback(status); 161 } 162 catch (RuntimeException ex2) { 163 logger.error("Application exception overridden by rollback exception", ex); 164 throw ex2; 165 } 166 catch (Error err) { 167 logger.error("Application exception overridden by rollback error", ex); 168 throw err; 169 } 170 } 171 172 } 173 | Popular Tags |