Programmatic transaction management

Programmatic transaction management

23 May 2013

I wanted to programmatically execute code inside a transaction and perform a rollback. This is useful to me when running tests in isolation preventing them from leaving data in the database.

Spring .NET

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.PropagationBehavior = TransactionPropagation.Required;
ITransactionStatus status = transactionManager.GetTransaction(def);
try
{
  // execute your business logic here
} finally
{
  transactionManager.Rollback(status);
}

Spring JAVA

PlatformTransactionManager pm = (PlatformTransactionManager) this.getBean("transactionManager");
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus transaction = pm.getTransaction(def);     
try {
    // execute your business logic here
}
finally {
    pm.rollback(transaction);
}
Frameworks IoC Spring