The fundamental concept in understanding Persistence Context in Spring Data JPA.
Spring Data JPA is a framework that simplifies the data access layer based on the JPA standard, providing many convenient methods and tools for interacting with databases.
Before we understand the Persistence Context of Spring Data JPA, let’s first take a look at the Persistence Context of JPA.
The Persistence Context is a critical concept in JPA, serving as a container for managed entity objects. It tracks the state of entity objects and their operations on the database. Each entity object in a Persistence Context has a unique identifier, allowing it to be located within the context.
The core concepts of the Persistence Context include the following:
- EntityManager: EntityManager serves as the entry point for Persistence Context, responsible for managing the lifecycle of persistent entity objects and performing CRUD operations on the database.
- The state of entity objects: There are three states for entity objects in the Persistence Context: transient, managed, and detached.
- Transient state: an entity object is not yet associated with the Persistence Context and does not have the ability to interact with the database.
- Managed state: signifies that the entity object is associated with a Persistence Context and can be operated on for CRUD operations.
- Detached state: Indicates that the entity object has been disconnected from the Persistence Context but still exists in the database.
- Primary cache: In the Persistence Context, there is a primary cache that stores managed state entity objects. When querying entity objects, it first searches in the primary cache. If the object is found, it is returned directly; otherwise, it will query the database.
- Dirty checking: When the properties of a persistent entity change, the Persistence Context automatically synchronizes the changed properties with the database. This process is known as dirty checking.
- Lazy loading: The Persistence Context supports lazy loading, meaning that database queries are only performed when accessing associated objects of entity objects, thereby reducing unnecessary database access.
In Spring Data JPA, the Persistence Context of JPA is encapsulated to simplify database operations through annotations and methods. It makes database access more convenient without the need to manually write repetitive code.