Persistence context and lazy loading
What you will learn
A persistence context manages entity instances and tracks their changes. Its lifetime defines which data can safely be accessed.
- Distinguish new, managed, detached and removed states.
- Explain persist, merge, detach, flush and commit.
- Map lazy data inside the transaction.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. JPA examples require the separate pinned companion Maven project. Their predicted results are not execution evidence.
Identity map model
public class Main { record Item(long id) {} public static void main(String[] args) {var context = new java.util.HashMap<Long,Item>();var first = context.computeIfAbsent(1L,Item::new);var again = context.computeIfAbsent(1L,Item::new);context.clear(); var next = context.computeIfAbsent(1L,Item::new);System.out.println(first == again); System.out.println(first == next); }}Expected output:
truefalseA map illustrates context-local identity. It is not a JPA cache or database test.
Context and lifecycle
Within one persistence context there is at most one managed instance for a given persistent identity. persist makes a new entity managed; find looks up an entity by key; remove schedules a managed entity for removal. detach or clear stops tracking a managed object; closing an application-managed EntityManager also detaches entities. merge copies state to a managed instance and returns it; the original detached object stays detached. Do not share EntityManager across threads. Managed changes are detected without calling save after every field update. A Spring service transaction typically provides the context boundary; declared repository queries need appropriate transaction configuration.
Synchronization and fetching
Flush synchronizes pending state with the database, and can fail before commit; a later rollback can undo transactional SQL. AUTO flush ensures relevant changes are visible to queries; COMMIT flush happens before commit and query visibility is not generally guaranteed. LAZY is a hint, EAGER a requirement; a provider may load lazily mapped data early. Accessing unfetched Hibernate proxies outside an open context may throw LazyInitializationException. Map to DTOs inside the transaction or request required data explicitly. Turning everything EAGER or leaving open-in-view on can hide unbounded queries. The lab disables open-in-view; readOnly is an optimization hint, not a universal write prohibition.
Copy detached data into a managed model
public class Main { static class Item { int stock; Item(int stock) { this.stock=stock; } } public static void main(String[] args) {var detached = new Item(4); var managed = new Item(detached.stock);detached.stock = 9; System.out.println(managed.stock); System.out.println(detached == managed); }}Expected output:
4falseA copy illustrates why changing the original after merge is not a managed update.
Context lifecycle
Source-reviewed, NOT RUN. File lab-fixtures/jpa-v40/src/main/java/example/catalog/ContextWalk.java; use the companion lab README.
package example.catalog;import jakarta.persistence.EntityManager;public final class ContextWalk { private ContextWalk() {} // Caller owns an active transaction and the EntityManager. public static void demonstrate(EntityManager em, Long id) { Product first = em.find(Product.class, id); Product second = em.find(Product.class, id); if (first == null || first != second) throw new IllegalStateException("Expected managed identity"); em.detach(first); if (em.contains(first)) throw new IllegalStateException("Expected detached entity"); Product managed = em.merge(first); if (!em.contains(managed) || managed == first) throw new IllegalStateException("Expected managed copy"); em.flush(); // synchronization, not commit }}Predicted behavior: Repeated find returns the managed instance, detach removes tracking, merge returns managed state.
Requires an active transaction and existing ID.
Service boundary
Source-reviewed, NOT RUN. File lab-fixtures/jpa-v40/src/main/java/example/catalog/CatalogService.java; use the companion lab README.
package example.catalog;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import org.springframework.data.domain.*;@Servicepublic class CatalogService { private final ProductRepository repository; public CatalogService(ProductRepository repository) { this.repository = repository; } @Transactional(readOnly=true) public ProductView find(String sku) { Product p = repository.findBySku(sku).orElseThrow(); return new ProductView(p.getSku(), p.getStock(), p.getCategory().getName()); } @Transactional(readOnly=true) public Page<ProductView> page(int page, int size) { if (page < 0 || page > 10000 || size < 1 || size > 100) throw new IllegalArgumentException("Invalid page"); return repository.summaries(0, PageRequest.of(page,size)); } @Transactional public void reserve(Long id, int amount) { Product p = repository.findById(id).orElseThrow(); p.reserve(amount); // managed change; version checked at flush/commit } @Transactional public void reserveWithLock(Long id, int amount) { repository.lockById(id).orElseThrow().reserve(amount); }}Predicted behavior: DTO is constructed before leaving the transaction.
Call through the Spring proxy; self-invocation does not start a new proxy-managed transaction.
Common mistakes
Do not use the original detached instance after merge expecting tracked changes, equate flush with commit, or assume every LAZY attribute is unloaded.
Practice
Build a tiny identity map, look up key 2 twice, clear it and look up again; print true then false.
Expected output:
truefalseCompare with the manual review criteria.
Official reading: Spec · Context · Transactions. ORM execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Persistence context and lazy loading — knowledge check
JPA mapping and persistence reasoning.
What does merge return?
What does flush guarantee?
What does LAZY mean in JPA?
Where should a lazy DTO be mapped?
Can one EntityManager be shared freely among threads?