Thursday, November 3, 2011

Rolling Back Transactions

While doing a spot check on code and configuration – I noticed that the developer wasn’t throwing a runtime exception nor was he setting rollbackOnly in a CMT EJB.

I was told that any exception will rollback a transaction and it is not possible to setRollbackOnly, and there are only 4 types of transaction attributes on CMT. Wrong, wrong and wrong.

1. If your code throws an application exception – the container expects the bean to handle it. However, if your bean throws a runtime exception (or subclass), like javax.ejb.Exception – the container will rollback the transaction.

2. If you don’t want to throw RTEs all around your code – and/or you have massive catch all exception code blocks, you should context.setRollbackOnly – to rollback transactions.

3. There are various transaction attributes – 6 to be exact: Requires, Requires New, Supports, Not Supported, Never & Mandatory. Never and Mandatory are opposite to one another. Requires starts a transaction if not called with one, Mandatory will throw an exception if called without a transaction, Supports will use one if there is one, but won’t complain….rest are self explanatory.

What’s most important about Transactions are how the transaction propagates in both directions (commit and more importantly rollback)