EntityManager Introduction#
What Is The EntityManager?#
-
EntityManager
: The resource manager that maintains the active collection of Entity objects that are being used by the application. TheEntityManager
handles the database interaction and metadata forobject-relational mappings (ORM)
. An instance of anEntityManager
represents a Persistence Context.- An
application in a container
can obtain theEntityManage
through injection into the application or by looking it up in the Java component name-space. - If the application manages its persistence, the
EntityManager
is obtained from theEntityManagerFactory
.
- An
-
In JPA, the
EntityManager
interface is used to allow applications to manage and search for entities in the relational database.- The
EntityManager
is an API that manages the life-cycle of Entity instances. AnEntityManager
object manages a set of entities that are defined by a Persistence Unit. EachEntityManager
instance is associated with apersistence context
. Apersistence context
defines the scope under which particular entity instances are created, persisted, and removed through the APIs made available byEntityManager
. In some ways, apersistence context
is conceptually similar to a transaction context. - The
EntityManager
tracks all Entity objects within apersistence context
for changes and updates that are made, and flushes these changes to the database. Once apersistence context
is closed, all managed entity object instances become detached from thepersistence context
and its associatedentity manager
, and are no longer managed. Once an object is detached from apersistence context
, it can no longer be managed by anentity manager
, and any state changes to this object instance will not be synchronized with the database. - There's always a new
Persistence Context
if there's a newEntityManager
.
- The