Sub topic 2
What the persistence context does
This chapter assumes you know basic JPA mapping (@Entity, @Id, @OneToMany, @ManyToOne), Spring Data JPA repositories, and how @Transactional works in Spring Boot. It uses the Author and Book model from the previous chapter.
The working model
The persistence context is the set of entity instances that one EntityManager (in Hibernate, one Session) currently manages. You can think of it as a map keyed by entity type and id. In a Spring Boot application it normally lives as long as the current transaction. When the transaction ends, the context closes and its entities become detached.
You rarely create it yourself. Spring opens it when a @Transactional method starts and closes it when that method returns. Repository calls inside the method share the same context.
What it gives you
The persistence context does three jobs that matter for performance.
- Identity guarantee. Within one context there is at most one instance per entity id. Loading
Author1 twice returns the same Java object. - First-level cache. A lookup by id checks the context first. If the entity is already there, Hibernate skips the SQL. This applies to
findByIdandgetReferenceById, not to JPQL queries, which always hit the database (though the rows they return are matched to instances already in the context). - Dirty checking. Hibernate keeps a snapshot of each managed entity's state. At flush time it compares the entity to its snapshot and issues an
UPDATEfor any difference. You do not callsavefor an entity you loaded in the same transaction.
@Transactional
public void rename(Long id, String newName) {
Author author = authorRepository.findById(id).orElseThrow();
author.setName(newName);
// No save() call. Hibernate detects the change and updates on flush.
}This example assumes Author has a setName method, which the previous chapter's listing left out.
Entity states
An entity is in one of four states relative to the context.
| State | Meaning |
|---|---|
| Transient | A new object that the context has never seen. It has no row. |
| Managed | Tracked by the open context. Changes are flushed automatically. |
| Detached | Was managed, but the context has closed. Changes are not tracked. |
| Removed | Scheduled for deletion at flush. |
Why this matters for N+1
Lazy associations are loaded through the persistence context. When you call author.getBooks(), the field holds a collection proxy. The first access to its contents asks the context's session to run a query. That only works while the context is open.
This has two consequences you will see in later chapters:
- Inside a transaction, every lazy access can trigger a query. A loop over many authors can trigger one query per author.
- Outside a transaction, with the context closed, the same access throws
LazyInitializationException, unless Open Session in View keeps the context open longer.
Author a = authorRepository.findAll().get(0); // context closed after the repository call if no outer transaction
a.getBooks().size(); // fails with LazyInitializationException when open-in-view is offThe context is also not free. Every managed entity costs memory for its snapshot, and flush time grows with the number of managed entities. Loading thousands of entities only to read them is slower than it looks, which is one reason DTO projections appear later in this tutorial.
Exercise
Inside one @Transactional method, you call authorRepository.findById(1L) twice. How many SELECT statements does Hibernate run for these two calls, and why?
Show answer
One. The first call loads the author and stores it in the persistence context. The second call finds the entity in the context (the first-level cache) and returns the same instance without querying the database.
Exercise
A service method has no @Transactional annotation. It calls authorRepository.findAll() and then getBooks().size() on the first result, with spring.jpa.open-in-view=false. What happens, and why?
Show answer
It throws LazyInitializationException. The repository call ran in its own short transaction, and its persistence context closed when it returned. The author is detached, so the lazy books collection has no open session to load from.