Monday, May 6, 2013

Using transaction attributes in EJB 3.1 - Container Managed Transactions

When somebody refers to container managed transactions, what we understand is that the EJB container is responsible of managing transactionality for the methods inside EJB's deployed in the EJB container.

The theory behind transaction management in EJB 3.1 is not brief and probably my post would become to long if I tried to explain other important concepts. In this post I want to just focus on an important concept known as the transaction attribute.

To simplify this concept, I will refer to it, as a configuration given to a method/function within an EJB, that will tell the EJB container what to do with the incoming transaction when that method is called.

The thing that will determine what will occur with the transaction when a certain transaction attribute is used will be the transactional context from where the method was called. In other words, if the enterprise method annotated with a certain attribute was called from a non-transactional(e.g a web page) will manage the transaction differently than if it was called from a transactional context(e.g another EJB). And this is the reason why sometimes we have to choose wisely our transaction attributes.

To use transaction attributes in our EJB's its very simple, all you need to do is use an annotation:
 @Stateful  
 public class SomeBean implements SomeInterface {  
   @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)  
   public void someMethod(){  
    //...  
   }  
   //...  
 }  

Now that we know how to annotate the methods, lets see what will occur when each of the transaction attributes is used:

REQUIRES_NEW
When the calling method is not in a transaction: Starts a new transaction.
When the calling method is in a transaction:  Suspends the existing transaction and creates a new one.

REQUIRED

When the calling method is not in a transaction: Starts a new transaction.
When the calling method is in a transaction:  Executes in existing transaction.

NEVER

When the calling method is not in a transaction: It will execute with no transaction.
When the calling method is in a transaction:  It will throw an exception.

NOT_SUPPORTED

When the calling method is not in a transaction: It will execute with no transaction
When the calling method is in a transaction: It will execute with no transaction(No exception will be thrown)  

SUPPORTS

When the calling method is not in a transaction: It will execute with no transaction.
When the calling method is in a transaction:  Executes in existing transaction.

MANDATORY

When the calling method is not in a transaction:  It will throw an exception.
When the calling method is in a transaction: Executes in existing transaction(Execution continues because the caller was already in a transaction).




3 comments:

Share with your friends