Wednesday, 8 February 2017

Spring Transactions management tips

Here is two ways to manage transactions in spring:

1) Programmatic transaction with TransactionTemplate class

TransactionTemplate txTemplate = new TransactionTemplate(txManager);
txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
txTemplate.execute(new TransactionCallback<object>() {
    public Object doInTransaction(TransactionStatus status) {
        // do stuff
    }
});

-be aware that A RuntimeException thrown by the callback is treated as a fatal exception that enforces a rollback. Such an exception gets propagated to the caller of the template.


2) Declarative with @Transactional annotation

- default propagation  is Propagation.REQUIRED

-default configured to rollback just Unchecked exceptions (ex RuntimeException), to rollback Exception need to use it like this:

@Transactional(rollbackFor = Exception.class)

-also method should be public, spring will wrap your method with proxy on context start and will add commit/rollback logic.

 -call to transnational method should be made from different class not from the same class, it is limitation of CGLIB (library that is doing method wrapping by the way you can use AspectJ)

- exception saying that "the transaction was marked as rollback only" it is because setRollbackOnly() method was called by exception (by the way you can call it too in previous approach), you can prevent it like this, or start new transaction for each part that should be handled independently

@Transactional(rollbackFor=MyException.class, noRollbackFor=MyException2.class)

-the Service is the best place for putting @Transactional

References:
16. Transaction Management

No comments:

Post a Comment