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. TheEntityManagerhandles the database interaction and metadata forobject-relational mappings (ORM). An instance of anEntityManagerrepresents a Persistence Context.- An
application in a containercan obtain theEntityManagethrough injection into the application or by looking it up in the Java component name-space. - If the application manages its persistence, the
EntityManageris obtained from theEntityManagerFactory.
- An
-
In JPA, the
EntityManagerinterface is used to allow applications to manage and search for entities in the relational database.- The
EntityManageris an API that manages the life-cycle of Entity instances. AnEntityManagerobject manages a set of entities that are defined by a Persistence Unit. EachEntityManagerinstance is associated with apersistence context. Apersistence contextdefines the scope under which particular entity instances are created, persisted, and removed through the APIs made available byEntityManager. In some ways, apersistence contextis conceptually similar to a transaction context. - The
EntityManagertracks all Entity objects within apersistence contextfor changes and updates that are made, and flushes these changes to the database. Once apersistence contextis closed, all managed entity object instances become detached from thepersistence contextand 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 Contextif there's a newEntityManager.
- The