The persistence context and lazy loading
First-level cache, dirty checking, flush, detached entities, open-in-view, and the N+1 query you can see in the logs.
The previous lesson said Hibernate watches your entities. This lesson is what does the watching, where it keeps them, and every surprise that follows from not knowing it is there.
That thing is the persistence context. In Spring it is one EntityManager, bound to one transaction, and it is the single most useful mental object in this whole course: almost every JPA question turns into an easy one once you ask what is in the persistence context right now, and is it still open?
Four states, and only one of them is watched
An entity is in exactly one of four states, and the transitions are what your code is actually doing:
- Transient — you made it with
new. Hibernate has never seen it. No id, no row. - Managed — it is in the persistence context. Changes to it will be written.
- Detached — it was managed, and the context closed. It still has data and an id, and nothing is watching it any more.
- Removed — scheduled for deletion at the next flush.
new Author(..). An ordinary object. Hibernate does not know it exists, and nothing you do to it matters yet. This is the only state in which you can change an id safely.
em.persist(a). Now it is managed. Note what did NOT happen: no INSERT was sent. Persist schedules the insert and assigns an id; the statement goes at flush.
a.setName(..). A plain setter on a plain object. There is no save() call here and there does not need to be — the context holds a snapshot of how the row looked when it loaded, and it will compare.
commit. Flush happens first: Hibernate compares every managed entity against its snapshot and writes what differs. THIS is where your UPDATE comes from.
em.close(). Detached. The object in your hand still has every value it loaded, so it looks fine — and any lazy relationship you never touched is now permanently unreachable.
Dirty checking: the UPDATE you did not write
Read this code and look for the save:
em.getTransaction().begin();
Author a = em.createQuery("select a from Author a where a.name = 'Bloch'", Author.class)
.getSingleResult();
a.setName("Joshua Bloch");
em.getTransaction().commit();### about to rename, with no save() call anywhere
### committing
Hibernate: update Author set name=? where id=?There is no save(), no update(), no merge(). The context kept a copy of the row as it was loaded, compared it at flush, found one field different, and wrote it.
This is the feature people find magical and then find frightening, and both reactions are right. It is why @Transactional(readOnly = true) is worth writing on read paths: it tells Hibernate not to keep those snapshots, which saves memory and makes an accidental write impossible.
Flush is not commit
Flush is sending the SQL. Commit is making it permanent. They usually happen together at the end, and the times they do not are worth knowing:
- Before a query that overlaps your pending changes, so the query sees them.
- When you call
em.flush()yourself. - At commit.
The consequence that catches people: a constraint violation surfaces at flush, not at the line that caused it. You set a field on line 20 and get the exception at line 60, where the transaction ends. This is why a stack trace from a flush is nearly useless for locating the cause and why em.flush() during debugging is a legitimate tool — it moves the error to the line you suspect.
The first-level cache caches objects, not queries
Every managed entity sits in a map keyed by its id, and that map is the first-level cache. It is always on and there is no way to turn it off.
### find(1) the first time
Hibernate: select author0_.id, author0_.name from Author author0_ where author0_.id=?
### find(1) again, same entity manager
### same object? true
### now a JPQL query for the same row
Hibernate: select author0_.id, author0_.name from Author author0_ where author0_.id=1
### same object as before? trueTwo things happened there and only one of them is the thing people remember.
find() twice produced one query. The second call never reached the database.
But the JPQL query did reach the database — the SQL is right there — and still returned the same object. That is the rule worth carrying: a query always runs; the cache decides which object you get back, not whether the SQL is sent. Hibernate ran the select, saw that row 1 was already managed, threw the freshly loaded values away and handed you the instance you already had.
Which has a sharp edge. If another transaction changed that row, your query brought the new values back from the database and then discarded them, because a managed instance always wins. Inside one transaction you see a consistent picture, which is usually what you want and is occasionally not what you expected.
Lazy loading, and the exception that is a design signal
A lazy relationship is a proxy: a generated subclass that holds an id and fetches on first use. That works while the context is open. Afterwards:
Author detached = em.createQuery(...).getSingleResult();
em.close();
detached.getBooks().size();### entity manager closed; now touching books
### org.hibernate.LazyInitializationException
### failed to lazily initialize a collection of role: demo.Author.books,
could not initialize proxy - no SessionThe usual reaction is to make the relationship eager, or to enable open-in-view so the context stays open until the response is rendered. Both make the symptom stop and both are the wrong move.
open-in-view is on by default in Spring Boot, and what it does is hold a database connection for the whole request — including the time spent serialising JSON — and let your view layer trigger queries. Queries then come from template rendering, where no one is looking for them, and the connection pool becomes the bottleneck under load.
The exception is telling you something true: this code is reading data that the transaction did not decide to load. The fix is to decide — fetch it in the query, or map to a DTO inside the transaction and let the detached object be a value rather than a live handle.
The N+1 problem, seen rather than described
Here is the shape, in a log. Four authors, two books each:
### the query you wrote
Hibernate: select author0_.id, author0_.name from Author author0_
### now touching each author's books
Hibernate: select ... from Book books0_ where books0_.author_id=?
Hibernate: select ... from Book books0_ where books0_.author_id=?
Hibernate: select ... from Book books0_ where books0_.author_id=?
Hibernate: select ... from Book books0_ where books0_.author_id=?
### total books: 8One query you wrote, four you did not, identical except for the parameter. That is the 1 and the N.
With four authors it is invisible. With five hundred it is five hundred and one round trips, each one a network hop, and the page takes eleven seconds for reasons the code does not show — because nowhere in the code is there a loop over queries. There is a loop over objects, and the queries are a consequence.
The four ways out, and what each one costs
1. A fetch join. Say it in the query:
select distinct a from Author a join fetch a.booksHibernate: select distinct ... from Author author0_ inner join Book books1_ on author0_.id=books1_.author_id
### books counted: 8 (authors: 4)One query. And now the trap, which is why this section exists at all. Add an author with no books and run the same query:
### authors in the table: [Bloch, Newcomer]
### join fetch returns: [Bloch]
### LEFT join fetch: [Bloch, Newcomer]join fetch is an inner join. The author with no books silently disappears from your results — no error, no warning, a correctness bug introduced by a performance fix. Write left join fetch unless you specifically mean to require children.
2. An entity graph. The same fetch, declared outside the query, so a repository method can stay a derived query:
EntityGraph<Author> g = em.createEntityGraph(Author.class);
g.addAttributeNodes("books");Hibernate: select distinct ... from Author author0_ left outer join Book books1_ on ...Note that Hibernate chose a left outer join here — so this one does not drop the childless author. In Spring Data it is an annotation on the repository method, @EntityGraph(attributePaths = "books"), which is the usual way you will meet it.
3. Batch fetching. @BatchSize(size = 25) on the collection turns N queries into N/25 queries using an in (?, ?, ?, ...). It does not eliminate the extra round trips, it makes them logarithmically fewer — which is the right answer when you genuinely need the children of many parents and a join would multiply rows badly.
4. Do not load entities at all. If the endpoint returns a summary, query a projection or a DTO directly. The fastest way to avoid the cost of loading an object graph is not to build one.
Under the hood: the persistence context as an identity map, and why the proxy needs a live session to fetch
The first-level cache section above already shows the behaviour — one object per row, a query that still runs but hands back the object you already had. The mechanism behind it has a name worth knowing: it is the identity map pattern, and the persistence context implements it literally as a map, keyed by (entity type, id), called the persistence context's entity map internally. Every time Hibernate is about to hand you an entity — from find(), from a JPQL query's result set, from a lazy fetch — it does not construct a fresh object and return it. It checks the entity map first. If an entry for that (type, id) already exists, Hibernate discards the row it just read from the result set (after using it only to detect changes, if a merge or refresh is in play) and returns the object already sitting in the map. That check is what "same object" in this lesson's example actually is: not a coincidence of caching, but the identity map refusing to create a second Java object for a row it already has one for.
This has a direct, testable consequence for object identity within one persistence context: entityManager.find(Author.class, 1L) == entityManager.find(Author.class, 1L) is true, always, for the lifetime of that context — and it is also why a persistence context should not outlive a single unit of work (one request, one transaction, roughly). Every entity it has ever touched stays in the entity map for the context's entire lifetime, growing unbounded across, say, a long-running batch job that loads millions of rows in one EntityManager — which is the actual mechanism behind the batch-processing advice to periodically clear() the persistence context: it is not clearing a cache for performance, it is releasing memory the identity map is otherwise obligated to hold onto for every entity it has ever returned.
The lazy proxy's dependency on a "live session" is the same map, approached from the other direction. A lazy @ManyToOne or @OneToMany is not populated with null and a promise to fill in later — it is populated with a real object: a dynamically generated subclass of the target entity (via Hibernate's own bytecode enhancement, conceptually the same subclass-proxy approach the low-level-design course's proxy lesson covers for Spring AOP) whose fields are null or empty, but which holds one thing that matters: a reference to the Session (the EntityManager's Hibernate-native equivalent) it was created inside. Every getter Hibernate generates on that proxy subclass is overridden to do the same thing before returning anything: check whether the proxy is already initialized, and if not, call back into that stored Session reference to run the actual SELECT and populate the real fields. LazyInitializationException is what happens when that overridden getter runs its check, finds the proxy uninitialized, and asks its stored Session reference to fetch — and the Session says it is closed. The proxy is not confused about what it needs; it is holding a reference to something that no longer exists in a usable state. This is exactly why "the transaction ended" and "the exception fires" are two different moments that can be arbitrarily far apart in your code: the proxy is perfectly happy sitting in a field, unread, for as long as you like — the exception only fires the instant something actually calls a getter on it after the session that could have serviced that call is gone.
Try it yourself
Reason through what the proxy actually holds
Two lines of code, in order, inside one transaction:
Author a = em.find(Author.class, 1L); // Author has a lazy @OneToMany books
em.getTransaction().commit(); // the transaction (and the persistence context) ends here
a.getBooks().size(); // this line throws LazyInitializationExceptionA teammate suggests the fix is to call a.getBooks().size() before commit(), one line earlier, and asks: "why does moving one line fix a NullPointerException-shaped problem — isn't books still going to be null either way until something loads it?"
Using the proxy mechanism above, is your teammate's mental model (a null field, populated by moving code earlier) accurate? What does the proxy actually hold before either line runs, and what changes about it after the fix?
The proxy is never null — it is a real object whose fetch either can or cannot reach a live session
The teammate's model is off in a specific, useful way: a.getBooks() never returns null and was never going to. It returns the lazy proxy the moment Author is loaded — a real, non-null object with empty/uninitialized internal state and a stored reference to the Session it was created inside. Calling .size() on it does not check for null; it runs the proxy's overridden method, which checks an initialized flag, finds it false, and uses its stored Session reference to run the actual SELECT ... FROM books WHERE author_id = ?. Moving .size() before commit() does not "populate a null field early" — it runs that same fetch at a moment when the stored Session reference is still open and can actually service the query, which is the only variable that changed between the failing version and the fixed one. After the fetch succeeds, the proxy's internal collection is populated and marked initialized, and every later call to .getBooks() — even after commit() — reads that now-populated internal state directly, with no further session access needed. The proxy's identity and its emptiness are unrelated: it is always a real object; whether calling it works depends entirely on whether the session it remembers is still alive at the moment something first touches it.
Misconceptions
- "The first-level cache and object equality (
equals/hashCode) are doing the same job." The identity map that produces "same object for the same row" uses==(literal object identity, via the(type, id)key), notequals()— it is a Hibernate-internal mechanism that runs before your entity'sequals()method is ever consulted. This is exactly why the entities-and-relationships lesson'sequals/hashCodeconcerns are a separate problem from anything the identity map handles: the identity map guarantees one object per row within a session;equals/hashCodeonly start mattering once you put entities into your ownHashSetorHashMap, where Java's collection framework — not Hibernate — is the thing calling those methods. - "Enabling
open-in-viewfixesLazyInitializationExceptionby making Hibernate smarter about fetching." It fixes the symptom by keeping the same session alive longer — through view rendering — so the proxy's stored session reference is still usable whenever a getter is finally called, wherever in the request that happens to be. Nothing about the identity map, the proxy, or the fetch mechanism changes; the scope of "still open" is just stretched to cover the whole request, which is precisely why this lesson already argues it trades a loud, locatable exception for a connection held open through serialization, with queries potentially firing from code (a view template) that has no idea it is triggering one.
Sources
- Martin Fowler, Patterns of Enterprise Application Architecture — the Identity Map pattern this lesson's first-level cache implements.
- Hibernate ORM User Guide, "Persistence Context" — the entity map, its lifecycle, and
clear()/detach()semantics for long-running units of work. - Hibernate ORM User Guide, "Association fetching" and "Bytecode Enhancement" — how lazy proxies are generated and what they hold.
- Vlad Mihalcea, "How does a JPA Proxy work" and "The Hibernate first-level cache" — the identity-map-versus-proxy distinction this section draws on.