Monday, 30 May 2011

EJB3 Transaction Annotation

This blog documents the EJB3 transaction annotations and was written because I had to add a transaction annotation to an EJB recently and the javadoc for JEE 5 didn’t document what the TransactionAttributeType values do; some are obvious if you’ve done this before, but I'm not psychic.

To specify either Containter Managed Transactions or Bean Managed Transactions use this annotation at class level:

      TransactionManagementType.CONTAINER | TransactionManagementType.BEAN)

For example:

@Stateful(name = "PlaceOrder", mappedName = "PlaceOrder")
// This will default to CONTAINER, but is here as a helpful hint
public class PlaceOrderBean implements PlaceOrder {

If you don’t specify this annotation, I believe that the container defaults to TransactionManagementType.CONTAINER.

Having specified your transaction management, you can add more fine grained control to individual methods in your EJB by using the @TransactionAttribute annotation.

        TransactionAttributeType.REQUIRED |
        TransactionAttributeType.REQUIRES_NEW |
        TransactionAttributeType.SUPPORTS  |
        TransactionAttributeType.MANDATORY  |
        TransactionAttributeType.NEVER  |

You apply the @TransactionAttribute annotation in the following way:

public Long confirmOrder() {

The default value for a @TransactionAttribute is TransactionAttributeType.REQUIRED

The table below defines in simple English what the TransactionAttributeType values are all about:

Attribute Type Description
REQUIRED If a caller transaction exists then join it else create a new transaction.
REQUIRES_NEW Create a new transaction, suspending the caller's transaction if one exists.
SUPPORTS If a caller transaction exists then join it else run without using a transaction.
MANDATORY If a caller transaction exists then join it else throw an EJBTransactionRequiredException.
NEVER If a caller transaction exists then throw an EJBException.
NOT_SUPPORTED If a caller transaction exists then suspend it. Run without a transaction.

Finally, just discovered that JEE 6 javadoc does add some explanation of these values - but it's not very good!

No comments: