JPA Persistence Context Explained
Fast recall
Quick revision
Core answer
Whether you understand JPA's core tracking mechanism: first-level cache identity guarantee and dirty checking
Confusing the first-level cache (per-transaction persistence context) with the optional shared second-level cache
Explain dirty checking — modifying a managed entity flushes automatically, so calling save() again is redundant
Interview-ready guide
Interview answer
After EntityManager finds Account 42, that Account object is managed. Changing its name inside a transaction can result in an UPDATE at flush without calling repository.save again. A second find of Account 42 in the same persistence context returns the same Java instance. This does not mean every query is cached or that the object always reflects direct database changes. Bulk updates and native SQL can make managed state stale until it is refreshed or cleared.
JPA Persistence Context Explained
Direct Answer
A persistence context is the set of entity instances managed by one EntityManager. It guarantees one managed instance per entity identity, tracks changes for flush, and serves as the first-level cache. In Spring it is commonly transaction-scoped, but JPA also supports extended persistence contexts, so it is not inherently identical to a transaction.
Code Example
@Service
public class OrderService {
private final OrderRepository orderRepository;
OrderService(OrderRepository r) { this.orderRepository = r; }
@Transactional
public void demo(Long orderId) {
var first = orderRepository.findById(orderId).orElseThrow(); // SELECT
var second = orderRepository.findById(orderId).orElseThrow(); // no SELECT (cached)
System.out.println(first == second); // true — same managed object
first.setStatus("SHIPPED"); // dirty checking → UPDATE at commit
}
}
Common Mistakes & Pitfalls
- Confusing first- and second-level cache — the persistence context is the first-level cache (per transaction, always on); the second-level cache is optional and shared across transactions.
- Calling save() after every change — redundant for managed entities; dirty checking handles it.
- Mutating detached entities — outside
@Transactional, entities are detached and changes won't sync. - LazyInitializationException — accessing a lazy relation after the context closes; load it inside the transaction or use a fetch join.
Check your understanding
Answer these without looking back at the article.
- What is dirty checking in JPA?
- What are the four entity states in JPA?
- What is the difference between first-level and second-level cache in JPA?
Related interview prep categories
2Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.