Sub topic 11
The persistence context and entity states
This chapter assumes you can map an entity, define a repository, and read basic Spring Boot code. It explains what happens to an entity object after you load or save it. Most "why was my change saved?" and "why was it not saved?" questions come from this model.
What the persistence context is
The persistence context is a per-transaction cache of entity instances that JPA keeps inside an EntityManager. It guarantees that, within one context, each database row maps to at most one Java object. It also remembers the state each entity had when it was loaded, so it can detect changes.
In a Spring Boot application, the EntityManager is created for you. Repository methods and @Transactional services share one persistence context for the duration of a transaction.
The four entity states
| State | Meaning | Tracked by the context? |
|---|---|---|
| New (transient) | Created with `new`, no identifier, no row | No |
| Managed | Loaded or saved in the current context | Yes |
| Detached | Was managed, but the context has closed | No |
| Removed | Scheduled for deletion at flush | Yes |
How Spring Data calls map to states
save() in SimpleJpaRepository checks whether the entity is new. For a generated identifier, an entity with a null id is new, so save() calls persist. Otherwise it calls merge.
merge does not make your instance managed. It copies the state onto a managed instance and returns that instance. Use the return value.
Book saved = books.save(detachedBook); // use "saved", not "detachedBook"Dirty checking
When an entity is managed, Hibernate keeps a snapshot of its loaded state. At flush time it compares the snapshot with the current values and issues an UPDATE for any difference. This is dirty checking.
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CatalogService {
private final BookRepository books;
public CatalogService(BookRepository books) {
this.books = books;
}
@Transactional
public void renameBook(Long id, String newTitle) {
Book book = books.findById(id).orElseThrow();
book.setTitle(newTitle); // managed entity: the change is tracked
}
}This example assumes Book has a setTitle method, which the earlier mapping example did not include. No save() call is needed. The UPDATE runs when the transaction commits.
First-level cache behavior
Within one context, loading the same id twice returns the same instance. The second findById does not hit the database.
@Transactional
public boolean sameInstance(Long id) {
Book first = books.findById(id).orElseThrow();
Book second = books.findById(id).orElseThrow();
return first == second; // true
}Common errors
- Changing a detached entity and expecting a save. Outside a transaction, the entity is detached. Edits are lost unless you call
save()or reload it inside a transaction. - Ignoring the return value of
save(). Aftermerge, the returned object is the managed one. - Adding
@Transactionalto a private or self-invoked method. Spring applies transactions through a proxy, so the annotation has no effect on those calls.
Exercise
A service method without @Transactional loads a Book with findById, calls setTitle, and returns. Is the new title written to the database, and why?
Show answer
No. Without a surrounding transaction, the repository call runs in its own short transaction and the persistence context closes when it returns. The Book becomes detached, so later changes are not tracked. Add @Transactional to the method, or call save() on the entity.