Sub topic 11
The persistence context and entity states
This chapter assumes you can write the Author and Book entities and a Spring Data repository, and that you know what @Transactional does at the annotation level. It explains what happens to an entity object between your code and the database. Most "mysterious" JPA behavior comes from this: changes saved without save(), save() returning a different object, and LazyInitializationException.
What the persistence context is
The persistence context is a set of entity objects that one EntityManager is currently tracking. In Hibernate it is called the session, and it is also known as the first-level cache. It does three jobs:
- Identity map. For each entity type and identifier, it holds at most one Java instance. Asking twice for
Book7 returns the same object. - Snapshot store. When it loads an entity, it keeps a copy of the field values. At flush time it compares the current values with the snapshot to find changes (dirty checking).
- Write queue. It collects pending inserts, updates and deletes, and sends them to the database later, in a chosen order.
Spring Data repositories do not have their own context. A repository call uses the EntityManager bound to the current transaction. Inside one @Transactional method, every repository call shares one persistence context. Without a transaction, each repository call gets a short-lived context of its own, and the entities it returns are detached as soon as the call ends. The next chapter covers transaction boundaries and flush timing.
The four entity states
Every entity instance is in exactly one state relative to a persistence context.
| State | Has an identifier? | Tracked by a context? | Has a database row? |
|---|---|---|---|
| Transient (new) | Usually not | No | No |
| Managed (persistent) | Yes | Yes | Yes, or an insert is pending |
| Detached | Yes | No | Yes (it may have changed since) |
| Removed | Yes | Yes, scheduled for delete | Yes, until flush |
Watching the states change
The following service uses EntityManager directly, because its method names (persist, merge, detach, remove) match the state diagram. It uses the Author entity from earlier chapters.
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class StateDemo {
@PersistenceContext
private EntityManager em;
@Transactional
public void walkThroughStates() {
Author author = new Author("Octavia E. Butler"); // transient
em.persist(author); // managed
// IDENTITY generation: the INSERT already ran, so the id is set
Long id = author.getId();
Author again = em.find(Author.class, id); // no SQL
System.out.println(again == author); // true: same instance
em.detach(author); // detached
Author reloaded = em.find(Author.class, id); // SELECT, new instance
System.out.println(reloaded == author); // false
Author merged = em.merge(author); // copies state onto managed instance
System.out.println(merged == reloaded); // true: the context already held id
System.out.println(merged == author); // false: author stays detached
em.remove(merged); // removed: DELETE at flush
}
}Key points from this run:
persistmakes the object you pass in managed. It does not return a copy.findchecks the context first. A secondfindfor the same id returns the same instance with no SQL.mergenever makes its argument managed. It returns the managed instance, which you must use from then on.removeonly schedules the delete. The row disappears when the context flushes.
With GenerationType.IDENTITY, persist runs the INSERT immediately, because the database creates the id. With sequence-based generation, the insert can wait until flush. This affects when constraint violations surface.
Dirty checking: updates without save()
When the context flushes, it compares each managed entity with its snapshot. For every entity that differs, Hibernate issues an UPDATE. That is why CatalogService.renameBook from earlier needs no save() call. To make it a real rename, Book needs a method that changes the title:
// in Book
public void rename(String newTitle) {
this.title = newTitle;
}@Transactional
public void renameBook(Long id, String newTitle) {
Book book = books.findById(id).orElseThrow();
book.rename(newTitle); // dirty: UPDATE runs at commit
}Dirty checking applies only to managed entities. If the same code ran without @Transactional, findById would return a detached Book, the change would be lost, and no error would appear.
What save() really does
SimpleJpaRepository.save decides between two operations:
- If the entity is new, it calls
em.persist(entity)and returns the same instance. - Otherwise it calls
em.merge(entity)and returns the managed copy.
"New" means the identifier is null (or, for primitive ids, zero). If the entity has a @Version attribute, a null version also counts as new. An entity with an assigned id and no version looks existing, so save runs merge, which issues a SELECT first and then an INSERT. That surprises people who assign UUIDs themselves.
Book detached = books.findById(7L).orElseThrow(); // outside a transaction: detached
detached.rename("New title");
Book saved = books.save(detached); // merge: SELECT, then UPDATE
System.out.println(saved == detached); // falseKeep using the returned value. Changes you make later to detached are not tracked, because only saved is managed.
Cascades and states
Cascade settings propagate state changes along associations. Author.books uses CascadeType.ALL, so persisting an Author also persists its transient books. Removing the author removes them. With orphanRemoval = true, a book removed from the books list is deleted at flush. Without a cascade, a managed Book that refers to a transient Author fails at flush with TransientPropertyValueException ("object references an unsaved transient instance").
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| `LazyInitializationException` | A lazy association was touched after the context closed | Load what you need inside the transaction (fetch join, entity graph, or a projection) |
| `detached entity passed to persist` | `persist` was called on an object that has an id | Use `save` or `merge`, or load the entity first |
| Update silently lost | Entity modified while detached | Make the method `@Transactional` so the entity stays managed |
| `TransientPropertyValueException` | A managed entity refers to a transient one | Persist the referenced entity first, or add a cascade |
| Unexpected extra UPDATE or stale read | Bulk `@Modifying` query bypassed the context | Use `clearAutomatically = true` or refresh |
Open Session in View
By default, Spring Boot web applications set spring.jpa.open-in-view=true. The persistence context then stays open for the whole web request, including view rendering. Lazy loading in controllers and serializers works, but database queries run outside your service layer, and each lazy access can add a query. Many teams set it to false and load exactly the data each use case needs. Turning it off is a good way to find lazy-loading bugs early.
Controlling the context
em.flush()sends pending changes to the database now, without committing.em.clear()detaches every managed entity. Use it in large batch loops so the context does not grow without bound.em.refresh(entity)overwrites the entity with the current row, discarding in-memory changes.em.contains(entity)tells you whether the entity is managed. It is useful when debugging state problems.
The context holds a strong reference to every managed entity until it closes. Loading 100,000 entities in one transaction keeps 100,000 objects and their snapshots in memory.
Exercise
A service method is not annotated with @Transactional. It calls books.findById(7L), then book.rename("Dune Messiah") on the result, and returns. The test shows the title unchanged in the database. Why, and what are two ways to fix it?
Show answer
Without a transaction, the repository call runs in its own short-lived persistence context, so the returned Book is detached when findById returns. Dirty checking only runs for managed entities, so the change is never flushed, and no error is raised. Fix 1: annotate the method with @Transactional so the Book stays managed and the change is flushed at commit. Fix 2: call books.save(book) after the change, which merges the detached entity (SELECT then UPDATE) and writes the title.