9.14.1 Entity lifecycle management with EntityManager
EntityManager is an object with an interface for executing the following operations for the database:
-
Registering and deleting entities.
-
Searching entities using the primary keys.
-
Issuing a query across the entities.
If you register an entity for EntityManager, the entity state is perpetuated in the database at an appropriate time such as when the transaction is committed.
Also, EntityManager has a relation with the persistence context that expresses the entity set. When you register the entity in EntityManager, the entity belongs to a specific persistence context. Also, EntityManager manages the entity lifecycle.
The entity set managed by EntityManager is defined with a unit called the persistence unit. You define the persistence unit in the application configuration file persistence.xml.
The notes on the persistence context and persistence unit are as follows:
-
The entity must be unique in the persistence context. Therefore, set one entity expressing the same line of the database in the same persistence context. Note that if the persistence contexts are different, you can have multiple entities expressing the same line in the database. For the locking method in the database in this case, see 9.10 Optimistic lock or 9.11 Pessimistic lock in JPQL.
-
Each persistence unit is mapped to a single database. For details on the definition, see 8.8 Definitions in persistence.xml.