Example

As discussed in “Benefits of using EJB Server transactions”, EJB Server transactions are most useful when your application uses intercomponent calls.

As an example, consider the scenario illustrated in “A transaction involving multiple components”. The pseudocode below shows the logic used to ensure that the work performed by the Registrar.reserveSeat() and StudentBilling.addToBill() occurs within the same transaction.

In the Registrar component, the reserveSeat() method must check the number of seats. If there is space for the new student, then the method adds the student, decrements the count of available seats, and sets a state of completeWork. If a seat is not an available, the method calls rollbackWork to roll back the current transaction.

Here is the pseudocode for Registrar.reserveSeat():

check number of seats
if enough seats
  decrement number of seats
  add student to enrollment list
  completeWork
else
  rollbackWork
end if

The transaction attribute for Registrar must be Requires Transaction so that the query for available seats and the update of available seats always occur in the same transaction.

In the StudentBilling component, the addToBill() method must verify the student’s credit. If the student does not already owe money, the method adds the cost to the semester bill and sets a state of completeWork. If the student owes money, the method calls rollbackWork to roll back the current transaction. Here is the pseudocode for StudentBilling.addToBill():

check student’s balance
if balance > 0
  add cost to bill
  debit balance
  completeWork
else
  rollbackWork
end if

The transaction attribute for StudentBilling must be Requires Transaction so that the balance query, the billing calculation, and the debit of the student’s balance always occur in the same transaction.

In the Enrollment component, the enroll() method first calls Registrar.reserveSeat(). After Registrar.reserveSeat() returns, the method checks whether the transaction is still viable using the isRollbackOnly primitive. If the transaction is viable, the method calls StudentBilling.addToBill(). Here is the pseudocode for Enrollment.enroll():

invoke Registrar.reserveSeat()
if isRollbackOnly returns true
  return
else
  invoke StudentBilling
  completeWork
endif

The transaction attribute for Enrollment must be Requires Transaction so that the work done by StudentBilling and Registrar occurs as a single transaction.