8.5.1 EntityManager and persistence context
The following figure shows a relationship between EntityManager and persistence context.
The EntityManager inserts the managed entity object in the persistence context and manages the entity objects. When the application passes the entity object to the persist method or updates the field value of the managed entity object, the status of the entity object in the persistence context is changed. EntityManager synchronizes the statuses of the entity objects in the persistence context and the database table just before the transaction is committed. In order to apply the statuses of the entity objects within the persistence context to the database table, the update SQL statements are issued collectively at this time. As a result, the database locking time is shortened, and therefore you can improve the concurrent executability and update the data efficiently.
- Organization of this subsection
(1) Types of EntityManager
You decide whether to use the container-managed EntityManager or the application-managed EntityManager depending on the relationship between the persistence context and transaction.
-
When the persistence context needs to be automatically propagated along with the JTA transaction
You use the container-managed EntityManager. If you use the container-managed EntityManager, the persistence context is automatically propagated along with the JTA transaction. Therefore, when multiple components are invoked in one JTA transaction, EntityManager used in the same JTA transaction can be associated with the same persistence context.
As a result, the application need not pass the EntityManager references to the arguments used when the references are invoked from one component in another component.
-
When the application needs to use the persistence context independently from the JTA transaction
You use the application-managed EntityManager. If you use the application-managed EntityManager, when you use another EntityManager in the same JTA transaction also, this EntityManager does not share the persistence context and has an independent persistence context.
(2) Types of persistence context
The persistence contexts are of two types depending on the lifetime:
-
Transaction scope persistence context
-
Extended persistence context
For the container-managed EntityManager, you can choose the type of persistence context. You specify the type of persistence context in the type attribute of @PersistenceContext. The default type is the transaction scope persistence context.
Note that the extended persistence context is always used for the application-managed EntityManager. You cannot choose the type of persistence context.