Featured Post

Scalability Techniques

Scalability is about the capability of a system to manage the increase workload of a system without causing qualities impact (i.e. perfo...

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