What are the main responsibilities of EntityManager?
The `EntityManager` is the central API in JPA for interacting with the persistence context. It manages the lifecycle of entity instances and is responsible for all database operations concerning entities within a specific persistence unit.
Overview
The EntityManager serves as an interface between the Java application and the persistence layer, essentially acting as a bridge to the underlying database through a JPA provider like Hibernate or EclipseLink. It's tied to a persistence context, which is a set of managed entities.
Core Responsibilities
Managing the Persistence Context
The EntityManager is the primary interface for managing the persistence context. It is responsible for tracking changes to entity instances, ensuring data consistency, and synchronizing these changes with the database. Entities within the persistence context are in a 'managed' state.
Performing CRUD Operations
- persist(entity): Makes a transient instance persistent.
- find(entityClass, primaryKey): Finds an entity by its primary key.
- merge(entity): Merges the state of a detached entity onto the current persistence context.
- remove(entity): Removes the entity instance from the persistence context and the database.
- refresh(entity): Refreshes the state of the entity from the database.
Executing Queries
It provides methods to create and execute queries in different forms, enabling data retrieval and manipulation beyond simple primary key lookups. This includes JPQL (Java Persistence Query Language), Criteria API, and native SQL queries.
Synchronization and Transaction Scope
The EntityManager operates within a transaction. All changes made to managed entities within a transaction are flushed to the database at transaction commit. It ensures that operations are atomic and consistent within the transactional boundaries.
Managing Entity Lifecycle
The EntityManager is responsible for triggering entity lifecycle events and callbacks (e.g., methods annotated with @PrePersist, @PostPersist, @PreUpdate, @PostUpdate, @PreRemove, @PostRemove, @PostLoad). These callbacks allow custom logic to be executed at different stages of an entity's lifecycle.