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 basic SQL. It builds on the Author and Book model from the previous chapter. The persistence context explains most of the surprising SQL you see in a Spring Boot application, so it is worth understanding before you look at lazy loading and N+1.
What it is
The persistence context is a set of managed entity instances that Hibernate tracks for one unit of work. In Hibernate it is the Session. In JPA it is the EntityManager. Both names refer to the same idea for our purposes: a first-level cache plus a change tracker.
The persistence context does three jobs:
- Identity map. For a given entity type and id, it holds at most one Java instance. Two lookups of
Author1 in the same context return the same object. - First-level cache. Once an entity is loaded,
findByIdfor the same id returns the instance from memory and runs no SQL. - Dirty checking. Hibernate keeps a snapshot of each managed entity's loaded state. At flush time it compares each entity with its snapshot and writes
UPDATEstatements for any that changed.
The first-level cache is always on and cannot be turned off. It is scoped to one context, so it is not shared between requests or threads.
Entity states
An entity instance is always in one of four states relative to a persistence context.
| State | Meaning | Tracked by dirty checking |
|---|---|---|
| Transient | Created with `new`, no id assigned by the database, not known to any context | No |
| Managed | Attached to an open context | Yes |
| Detached | Was managed, but the context closed or the entity was evicted | No |
| Removed | Scheduled for deletion at flush | Yes, until deleted |
The state that matters most for performance is detached. A detached entity keeps its already loaded fields, but nothing can load more data for it. Touching an uninitialized lazy association on a detached entity throws LazyInitializationException.
How Spring Boot scopes the context
You rarely create an EntityManager yourself. Spring binds one to the current transaction.
- With
@Transactional, Spring opens a persistence context when the transaction starts and closes it when the transaction ends. - All repository calls inside that transaction share the same context, so they share the same managed instances.
- A repository call made without an active transaction gets a short-lived context of its own, which closes when the call returns. Entities returned from it are detached immediately.
Spring Data repository methods such as findAll and save are themselves transactional. This means calling authorRepository.findAll() from a non-transactional method returns detached authors. The next chapter shows why that matters for lazy collections.
The following service shows the identity map and first-level cache working inside one transaction.
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class IdentityDemoService {
@PersistenceContext
private EntityManager entityManager;
@Transactional(readOnly = true)
public boolean sameInstance(Long authorId) {
Author first = entityManager.find(Author.class, authorId); // runs a SELECT
Author second = entityManager.find(Author.class, authorId); // served from the context
return first == second; // true
}
}The method returns true and issues one SELECT. The second find never reaches the database.
Flush and dirty checking
Hibernate does not send changes to the database as you make them. It queues them and sends them at flush time. By default (FlushModeType.AUTO) a flush happens:
- before the transaction commits;
- before a JPQL or HQL query that might be affected by pending changes;
- when you call
flush()explicitly.
Because of dirty checking, you do not need to call save on a managed entity to update it.
@Service
public class AuthorRenameService {
private final AuthorRepository authorRepository;
public AuthorRenameService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional
public void rename(Long id, String newName) {
Author author = authorRepository.findById(id).orElseThrow();
author.setName(newName); // no save() call
} // commit: Hibernate flushes and runs UPDATE author SET name=? WHERE id=?
}This sample assumes Author has a setName method, which the model in the previous chapter left out. Add one if you run it.
The cost of dirty checking is worth knowing. For every managed entity, Hibernate compares the current state with the snapshot at each flush. Loading 10,000 entities in a read-only operation means 10,000 snapshots in memory and 10,000 comparisons at flush, even if you change nothing.
Read-only transactions
@Transactional(readOnly = true) is a hint to Spring and Hibernate. With Hibernate it sets the session's flush mode to manual, so the flush and the dirty check are skipped. Hibernate also avoids keeping some of the snapshot data for entities loaded in a read-only session. The result is lower memory use and less CPU work for query-only methods.
Use it on service methods that only read. It does not stop the database from running the statements, and it does not make lazy loading cheaper. It only removes the change-tracking overhead.
Lazy loading depends on the context
A lazy association is represented by a proxy or a special collection (PersistentBag, for example). It holds the owner's id and a reference to the session that created it. When you first access it, Hibernate uses that session to run a SELECT.
This means lazy loading works only while the session is open. Two consequences follow:
- Inside a
@Transactionalmethod, touchingauthor.getBooks().size()works and runs one query. - After the transaction ends, the same call throws
LazyInitializationException(unless Open Session in View keeps the session open, which a later chapter covers).
Each lazy initialization is a separate SQL statement. The persistence context makes it convenient, because the query happens invisibly on first access. That same convenience is how a loop over authors turns into one query per author.
Common errors and gotchas
Stale reads from the first-level cache
Once an entity is in the context, a later find by id returns the cached instance without checking the database. If another transaction changed the row, you do not see it until the context ends or you call entityManager.refresh(entity). A JPQL query does run SQL, but for rows already in the context it still returns the existing managed instance and ignores the fresh column values.
Unbounded context growth
Every loaded entity stays in the context until it closes. A long batch job that loads many entities in one transaction will consume memory until it fails. Process in chunks and call entityManager.flush() followed by entityManager.clear() between chunks. clear() detaches everything, so do not use the old instances afterward.
Calling save on managed entities
save on a managed entity does nothing useful, because dirty checking already covers it. On a detached or new entity it matters. Spring Data's save calls persist for new entities and merge for existing ones. merge may run an extra SELECT to load the current state before copying values over.
Query results that look surprising
A query returning entities puts each result into the context. If the context already holds an entity with that id, you get the existing instance. This is why modifying an entity in memory and then running a query can produce results that reflect your unsaved change. It is also why Hibernate flushes before the query in AUTO mode.
Transaction boundaries hidden by self-invocation
@Transactional works through a Spring proxy. If one method in a class calls another method of the same class, the proxy is bypassed and the annotation on the second method has no effect. The code then runs without the transaction you expected, and entities may be detached sooner than you think.
Why this matters for N+1
The persistence context is what makes lazy loading possible and what makes it easy to misuse. Reading author.getBooks() looks like a field access, but it can be a database round trip. When you do that for every author in a list, you get one query for the list plus one per author. The next chapters build on this: first how fetch types decide when data loads, then how the N+1 pattern forms.
Exercise
In a single @Transactional method you call authorRepository.findById(1L) twice, then change the author's name with a setter and return without calling save. How many SELECT statements for the author run, and is the name change written to the database?
Show answer
One SELECT runs, because the second findById is served from the first-level cache. The name change is written, because the author is managed and dirty checking issues an UPDATE at flush when the transaction commits.
Exercise
A service method has no @Transactional annotation. It calls authorRepository.findAll() and then calls getBooks().size() on the first author, where books is a lazy collection. What happens, and why?
Show answer
It throws LazyInitializationException (assuming Open Session in View is off). The repository call ran in its own short transaction, so the context closed on return and the authors are detached. The lazy collection has no open session to load from.
Exercise
Why does @Transactional(readOnly = true) help a method that loads 5,000 entities and changes none of them?
Show answer
Hibernate sets the session to manual flush, so it skips the flush-time dirty check and does not need to compare 5,000 entities with their snapshots. This lowers CPU work and memory use. It does not reduce the number of SELECT statements.