Enterprise Java Development@TOPIC@

Chapter 102. Transactions

102.1. Transaction Examples
102.2. Transaction ACID Properties
102.3. EJB Transaction Scenarios
102.3.1. Scenario: Multiple DB Updates
102.3.2. Scenario: Update Multiple Databases
102.3.3. Scenario: Coordinate JMS with Database Transaction
102.4. Transaction Terms
102.5. JTA and JTS Specifications
102.5.1. Java Transaction API (JTA)
102.5.2. Java Transaction API (JTA) and Java Transaction Service (JTS)
102.6. EJB Transactions
102.6.1. Container-Managed Transactions (default)
102.6.2. Bean-Managed Transactions
102.7. Summary

Unit of work that accesses one more more resources (usually databases)

EJB is primarily a transaction framework/platform for application code

Figure 102.4. Container-Managed Transactions

Container-Managed Transactions
@Stateless

@TransactionManagement(TransactionManagementType.CONTAINER)
public class HotelMgmtEJB implements HotelMgmtRemote, HotelMgmtLocal {
...
    @PersistenceContext(unitName="ejbjpa-hotel")
    private EntityManager em;
    private HotelDAO dao;                                                                                                                                                                                                                                                                                                                                   
    private HotelMgmt hotelMgmt;
     
    @PostConstruct
    public void init() {
        dao = new JPAHotelDAO();
        ((JPAHotelDAO)dao).setEntityManager(em);
        hotelMgmt = new HotelMgmtImpl();
        ((HotelMgmtImpl)hotelMgmt).setHotelDao(dao);
    }
    @Override
    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public Room getRoom(int number) {
        return hotelMgmt.getRoom(number);
    }
    
    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)    
    public Guest checkIn(Guest guest, Room room) throws RoomUnavailableExcepton {
        return hotelMgmt.checkIn(guest, room);
    }

Container manages all aspects of transaction for CMT

For Container Managed Transactions (CMT), the transaction management code is in the Container and *not* within the method body of the EJB.


EJB code manages begin/commit aspects of transaction for BMT

For Bean Managed Transactions (BMT), the transaction management code is in the EJB method. This adds extra non-business code and even the simplest scenario begins to get complicated.