Distributed Transactions   «Prev  Next»
122
Lesson 7 Bean-managed transactions
Objective Program bean-managed transactions

EntityBeans may manage their own Transactions

In Jakarta EE 9, Entity Beans (specifically EJBs using Container-Managed Persistence or CMP) are a legacy technology and are no longer the recommended way to manage persistence or transactions. Jakarta EE has transitioned towards using JPA (Java Persistence API)[1] for managing persistence and CMT (Container-Managed Transactions) or BMT (Bean-Managed Transactions) for managing transactions.
However, in earlier versions of Jakarta EE (formerly Java EE), Entity Beans could manage transactions using two methods:
  1. Container-Managed Transactions (CMT): The container manages the transactions automatically. The EJB developer specifies the required transaction attributes (like `Required`, `RequiresNew`, etc.) in the deployment descriptor or by using annotations. The EJB itself doesn't need to interact directly with the transaction service.
  2. Bean-Managed Transactions (BMT): In this case, the bean is responsible for explicitly managing the transactions using the UserTransaction API. This allows more fine-grained control over when transactions start, commit, or roll back. The EJB interacts directly with the UserTransaction service provided by the container.

In Jakarta EE 9, you would typically handle transactions in one of the following ways:
  • For stateless or stateful session beans, you can still use CMT or BMT.
  • For persistence, the modern approach would be to use JPA, where transactions are generally managed by the EntityManager and the surrounding session bean or CDI context.

Entity Beans are considered deprecated, and JPA is the preferred choice for handling persistence and transactions directly in modern Jakarta EE applications.


Legacy J2EE Bean Management

In older versions of Java EE, Beans could manage their own transactions directly by communicating with the transaction service. The container provides access to the transaction manager through the UserTransaction getUserTransaction() method of javax.ejb.EJBContext. UserTransaction is in the javax.transaction package. The sample code below illustrates the retrieval of the UserTransaction object:
SessionContext sc =  ? // initialized when bean is created
...
javax.transaction.UserTransaction t = sc.getUserTransaction();

J2EE javadoc documentation Use the J2EE javadoc documentation to view the UserTransaction object details in your browser.

The methods of UserTransaction in our exampel are as follows:
begin() Create a new transaction and associate it with the current thread
void commit() Complete the transaction associated with the current thread
int getStatus() Obtain the status of the transaction associated with the current thread
void rollback() Roll back the transaction associated with the current thread
void setRollbackOnly() Modify the transaction associated with the current thread such that the only possible outcome of the transaction is toroll back
void setTransactionTimeout(int seconds) Modify the value of the timeout that is associated with the transactions started by the current thread in the begin method


Legacy J2EE Transaction Exceptions

The exceptions that can be thrown by these methods are as follows (all extend java.rmi.RemoteException):
  1. HeuristicCommitException: Indicates that some parts of a distributed transaction might have been committed while others might have been rolled back, leading to an uncertain outcome.
  2. HeuristicMixedException: Signals that some parts of a distributed transaction have been committed, some have been rolled back, and the status of others is unknown, resulting in an inconsistent global transaction state.
  3. HeuristicRollbackException: Indicates that some parts of a distributed transaction have been rolled back, and the status of others is uncertain, suggesting a potential global rollback.
  4. InvalidTransactionException: Thrown when an operation is attempted on a transaction that's in an invalid state, such as after it has already been committed or rolled back.
  5. NotSupportedException: Indicates that the requested transaction operation is not supported by the underlying transaction manager or resource.
  6. RollbackException: Signals that the transaction has been marked for rollback, typically due to an application error or explicit rollback request.
  7. SystemException: Represents a serious system-level error during transaction processing, often indicating an unexpected failure within the transaction manager or underlying resources.
  8. TransactionRequiredException: Thrown when an operation that requires an active transaction is attempted outside of a transactional context.
  9. TransactionRolledbackException: Indicates that the transaction has been rolled back, usually due to an error or exception during its execution.
For a more complete understanding of these exceptions, refer to the javax.transaction.documentation.

Class constants
The class constants that indicate the status of the transaction are as follows:
  1. STATUS_ACTIVE
  2. STATUS_COMMITTED
  3. STATUS_MARKED_ROLLBACK
  4. STATUS_NO_TRANSACTION
  5. STATUS_PREPARED
  6. STATUS_PREPARING
  7. STATUS_ROLLEDBACK
  8. STATUS_ROLLING_BACK
  9. STATUS_UNKNOWN
These constants are returned from the getStatus() method and indicate the status of the current transaction. Because transactions cannot be nested, an object only can partake in a single transaction at a time. getStatus() returns the current status of the current transaction.
The following diagram contains Bean managed Transactions and the session context method.

Java EE 8 Application Development

Transactions that are managed through Entity Beans

SessionContext and the save() method
SessionContext and the save() method

Line 09Using the SessionContext method getUserTransaction(), the program gets the UserTransaction object and stores its reference in ut.
Line 11 and 12This line verifies that there is no current transaction context using getStatus() method. The return is compared to the STATUS_NO_TRANSACTION class constant. If there is a transaction, the program throws a CustomerException.
Line 13 and 14 Begin a transaction within a try-catch block.
Line 17 The actual code to update the state of one or more recoverable resources would be inserted here.
Line 18 and 19 If any problem was discovered then the transaction will be rolled back.
Line 21 The transaction manager was asked to commit the transaction.

Business Object Architecture

The Business Object Architecture contains the components that implement the business entities in the system. Each of these components manages the data and business logic associated with a particular business entity. This includes the persistence of that object's data, typically to a relational database. This database access can be implemented by the container in the case of CMP (Container-Managed Persistence) Entity Beans or by the developer in the case of BMP (Bean-Managed Persistence) Entity Beans or regular Java classes. In the last two cases, in which the developer does the work, it is a best practice to isolate the database access into a separate data-access layer. If there is any data access outside of the business object model, this should also be included in this layer. This includes database queries that are run in order to retrieve read-only data for presentation to the user.
In the bank application, a business object could represent entities such as a customer, a bank account, or even an individual transaction on the bank account such as a withdrawal. These business objects can be implemented either as Java classes, Entity Beans, or some combination of the two. The persistence of each business object is abstracted out to the extent possible so that separate data objects, persistence frameworks, or Container-Managed Persistence services can be used to have the object data persist in the database.

J2EE documentation

Remember to look up any of the classes and methods in the javadoc j2ee documentation.
In the next lesson container-managed transactions will be discussed.

[1] JPA (Java Persistence API) : Java Persistence API (JPA) in Java EE 9 provides a standard way for Java applications to interact with relational databases, enabling developers to perform CRUD operations and manage object-relational mapping through annotations and a persistence unit configuration. In essence, JPA simplifies database interactions in Java EE 9 by bridging the gap between Java objects and database tables, fostering a more object-oriented approach to data persistence.
[2] transaction service: In Java EE, the transaction service provides a mechanism to ensure data integrity and consistency across multiple operations by grouping them into a single unit of work. It allows developers to either manage transactions explicitly using the Java Transaction API (JTA) or delegate transaction management to the container through declarative annotations, ensuring that either all operations within a transaction succeed or none of them do, thus preserving data integrity even in the face of errors or failures.

SEMrush Software