The programmatic approach is the component-managed transaction and the declarative transaction demarcation approach is the container-managed transaction.
The J2EE application uses the 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, 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 J2EE/CA's 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 can be used only in the EJB environment. The EJB 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.
Related Reading: For more information about the J2EE architecture and JTA specifications, see http://java.sun.com/j2ee/docs.html.