Featured Post

NoSQL use cases

Here are a simple summary of use cases for Cassandra, MongoDB and Redis MongoDB Storing Log Data Speed is the primary perfor...

Sunday, May 6, 2012

Container Managed Transaction (CMT) vs Bean Managed Transaction (BMT)

The main difference between BMT and CMT is:
  • BMT means the Bean manages the transaction.
  • CMT means the container manages transactions.

BMT Example


In the following example you can see ReservationService, it is a Session Stateless Bean that manages the transaction using explicitly calls as begin, commit and rollback.
ReservationServiceRemote.java

//package and import

@Remote
public interface ReservationServiceRemote {

 public Reservation prenota(String nomeFilm, int numPosti, int clientId);
}

ReservationService.java

//package and import

@Stateless
@TransactionManagement(TransactionManagementType.BEAN) 
public class ReservationService implements ReservationServiceRemote {

 @Resource
 private UserTransaction tx;


 @Override
 public Reservation prenota(String nomeFilm, int numPosti, int clientId) {
  Reservation reservation =null;
  try {
   tx.begin();
   System.out.println("transaction begin");
    reservation= .....
   tx.commit();
   System.out.println("transaction commit");
  } catch (Exception e) {
   try {
   tx.rollback();
   System.out.println("transaction rollback");
   } catch (IllegalStateException e1) {
       // log
   } catch (SecurityException e1) {
       // log
   } catch (SystemException e1) {
       // log
   }
  } 
  return reservation;
 }

Example CMT


CMT doesn't need to use explicitly begin, commit, etc.. The container does it for you. As you can see FilmService is a Stateless Session Bean that uses @PersistenceContext annotation to inject the EntityManager. There's no transaction explicitly opened, it's done by the container as soon as you use a method of the EntityManager. The transaction commits only at the end of the method.

FilmServiceRemote.java

//package and import

@Remote
public interface FilmServiceRemote{
 
 public void addFilm(String filmName);
 
}

FilmService.java

//package and import

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class FilmService  implements FilmServiceRemote{

 @PersistenceContext(unitName = "reservations")
 private EntityManager entityManager;
 
 public void addFilm(String name) {
  Film film = new Film();
  film.setName(name);
  entityManager.persist(film);
 }
 
}


Transaction Propagation


Here it is some rules:
  • A Bean Managed Transaction cannot be shared with other Beans that use BMT.
  • A Container Managed Transaction can join the transactions opened by Beans that make use of a BMT.

No comments :

Post a Comment