Using a platformtransactionmanager, Recommendation – HP Integrity NonStop J-Series User Manual

Page 71

Advertising
background image

// use constructor-injection to supply the PlatformTransactionManager
public SimpleService(PlatformTransactionManager transactionManager) {
Assert.notNull(transactionManager, "The 'transactionManager' argument must not be null.");
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
public Object someServiceMethod() {
return transactionTemplate.execute(new TransactionCallback() {
// the code in this method executes in a transactional context
public Object doInTransaction(TransactionStatus status) {
updateOperation1();
return resultOfUpdateOperation2();
}
});
}
}

If there is no return value, use the convenient TransactionCallbackWithoutResult
class via an anonymous class:

transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
updateOperation1();
updateOperation2();
}
});

Code within the callback can roll the transaction back by calling the
setRollbackOnly()

method on the supplied TransactionStatus object.

transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
updateOperation1();
updateOperation2();
} catch (SomeBusinessExeption ex) {
status.setRollbackOnly();
}
}
});

Using a PlatformTransactionManager

You can perform transaction management using
org.springframework.transaction.PlatformTransactionManager

by completing

the following steps:-
1.

Pass the implementation of the PlatformTransactionManager to the bean.

2.

Use the TransactionDefinition and TransactionStatus objects to initiate
transactions, rollback, and commit.

DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// explicitly setting the transaction name is something that can only be done programmatically
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
try {
// execute your business logic here
}
catch (MyException ex) {
txManager.rollback(status);
throw ex;
txManager.commit(status);

Recommendation

1.

Programmatic transaction management is usually a good idea only if you have a small number
of transactional operations. For example, if you have a web application that requires
transactions only for certain update operations, you may not want to set up transactional
proxies using Spring or any other technology. In this case, using the TransactionTemplate

Spring Framework Configurations

71

Advertising
This manual is related to the following products: