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.

//package and import

public interface ReservationServiceRemote {

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


//package and import

public class ReservationService implements ReservationServiceRemote {

 private UserTransaction tx;

 public Reservation prenota(String nomeFilm, int numPosti, int clientId) {
  Reservation reservation =null;
  try {
   System.out.println("transaction begin");
    reservation= .....
   System.out.println("transaction commit");
  } catch (Exception e) {
   try {
   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.


//package and import

public interface FilmServiceRemote{
 public void addFilm(String filmName);


//package and import

public class FilmService  implements FilmServiceRemote{

 @PersistenceContext(unitName = "reservations")
 private EntityManager entityManager;
 public void addFilm(String name) {
  Film film = new 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