Home

 

Entity manager

Entities cannot persist themselves on the relational database; annotations are used only to declare a POJO as an entity or to define its mapping and relationships with the corresponding tables on the relational database.

JPA has defined the EntityManager interface for this purpose to let applications manage and search for entities in the relational database. The EntityManager primary definition includes the following elements:

An API manages the life cycle of entity instances (extract):

persist-Insert a new entity instance
find-Find an instance by key
remove-Delete an instance
merge-Merge changes of an entity
flush-Synchronize with database
refresh-Reload from database
createNamedQuery-Create an instance of a predefined query

Each EntityManager instance is associated with a persistence context.

A persistence context defines the scope under which particular entity instances are created, persisted, and removed through the APIs made available by an EntityManager.

An object manages a set of entities defined by a persistence unit.

The entity manager tracks all entity objects within a persistence context for changes and updates made, and flushes these changes to the database. After a persistence context is closed, all managed entity object instances become detached from the persistence context and its associated entity manager, and are no longer managed.

Managed and unmanaged entities: An entity object instance is either managed (attached) by an entity manager or unmanaged (detached):

When an entity is attached to an entity manager, the manager monitors any changes to the entity and synchronizes them with the database whenever the entity manager decides to flush its state.

When an entity is detached, and therefore is no longer associated with a persistence context, it is unmanaged, and its state changes are not tracked by the entity manager and synchronized with the database.

ibm.com/redbooks