Global transaction support in client applications
On the Java™ EE platform, you can use either a programmatic or a declarative transaction demarcation approach to manage transactions in your application.
The programmatic approach is the component-managed (or bean-managed) transaction and the declarative transaction demarcation approach is the container-managed transaction.
Component-managed (or bean-managed) transactions
The Java EE application uses the Java Transaction API (JTA) javax.transaction.UserTransaction interface to demarcate a transaction boundary to a set of changes to the protected resource programmatically. Component-managed transactions can be used in both the servlet and the EJB environment. In the case of an EJB component, you set the transaction attribute in its deployment descriptor as TX_BEAN_MANAGED.
A transaction normally begins with a UserTransaction.begin() call. When the application component is ready to commit the changes, it invokes a UserTransaction.commit() call to coordinate and commit the changes. If the application component must roll back the transaction, it invokes UserTransaction.rollback() and all changes are backed out. For example:
// Get User Transaction
javax.transaction.UserTransaction transaction =
ejbcontext.getUserTransaction();
// Start transaction
transaction.begin();
// Make changes to the protected resources.
// For example, use the Java EE or JCA CCI Interaction interface
// to submit changes to an EIS system(s)
interaction.execute(interactionSpec, input, output);
if (/* decide to commit */) {
// commit the transaction
transaction.commit();
} else { /* decide to roll back */
// rollback the transaction
transaction.rollback();
}
Container-managed transactions
Container-managed transactions can be used only in the EJB environment. The EJB component specifies a container-managed transaction declaratively through the transaction attribute in the deployment descriptor (such as TX_REQUIRED). A container-managed transaction is managed by the EJB container. The container calls the appropriate methods (such as begin, commit, or rollback) on behalf of the EJB component. This declarative approach simplifies the programming calls in the EJB component.