Saturday, July 2, 2011

Transactions

Today I found a really good way to deal with transaction management in EJB 3.0 and Hibernate.
I found it on a Java Developer's Forum called "Coderanch", here: http://www.coderanch.com/t/216252/ORM/java/hibernate-Container-Managed-Transactions-CMT

It proposes the usage of container managed transactions (CMT) on the level of EJB beans together with the transactions in Hibernate session.
Like this:  When a CMT transaction in an EJB bean is running, and the Hibernate transaction is started, it joins the CMT one. 
I was worrying there might be some conflict about it, but looks like everything is fine. It is just necessary to explicitly set the transaction annotation for each bean:



import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import static javax.ejb.TransactionAttributeType.*;


@Stateless
@TransactionManagement(value=TransactionManagementType.CONTAINER)   //CMT type transaction
@TransactionAttribute(value=REQUIRED)                                                           //Required as its attribute


public class MyEJB implements MyEJBRemote {
  .... }


******************* Update: *******************
By some reason the NetBeans 6.9 doesn't resolve the input for this code correctly, so in case you copy it please make sure you copy the imports too. 

No comments:

Post a Comment