ORM and JPA: the persistence context, dirty checking and N+1
The persistence context and first-level cache, the four entity states, persist vs merge, dirty checking and flushing, lazy vs eager loading, the N+1 problem and four ways to fix it: fetch joins, entity graphs, batch fetching and DTO projections.
On this page
1. The problem
GET /courses returns 50 courses with teacher names: Hibernate fires 51 SQL statements. Locally it's fast, so nobody notices; in production, with 2 ms of network latency per statement and 200 concurrent requests, the connection pool runs dry. The same week, a controller "formats" titles for the response, and the titles in the DB change too.
2. Key idea
The persistence context is a map (entity type, id) → object tied to an EntityManager; in Spring it lives for one transaction by default. findById(1) twice issues one SQL statement and returns the same object.
On load, Hibernate keeps a snapshot; on flush, any field that differs produces an UPDATE. Flush sends SQL but stays within the transaction; only commit makes it durable. So changing a managed entity's field to "format" a response really changes the DB.
| N+1 fix | Use when | Don't use when |
|---|---|---|
Fetch join (join fetch) |
one use case needs the relationship, no collection paging | collections + Pageable; two Lists at once |
@EntityGraph |
derived queries, no JPQL wanted | same limits as fetch join |
default_batch_fetch_size |
an app-wide safety net that works with paging | you need exactly 1 query |
| DTO projection | read-only screens, a few columns | you need to modify entities |
| EAGER | almost never | every screen pays; with JPQL, EAGER is N+1 too |
Default every relationship to LAZY, including @ManyToOne and @OneToOne (EAGER by default). Touching a lazy relationship after the context closes throws LazyInitializationException: fetch what you need in the service, don't switch to EAGER or open-in-view.
3. In Java
The same screen two ways: N+1 and a single statement.
// N+1: 1 query for courses, then 1 query per course for its teacher
@Transactional(readOnly = true)
public List<CourseSummary> listCourses() {
return courseRepository.findAll().stream()
.map(c -> new CourseSummary(c.getId(), c.getTitle(), c.getTeacher().getName()))
.toList(); // 50 courses -> 51 statements
}
// One statement: DTO projection, no entities loaded, no dirty checking
public record CourseSummary(Long id, String title, String teacherName) {}
@Query("""
select new com.vinhnq.elearning.dto.CourseSummary(c.id, c.title, t.name)
from Course c join c.teacher t where c.status = :status""")
List<CourseSummary> findSummaries(@Param("status") CourseStatus status); // 1 statementDetecting N+1: spring.jpa.properties.hibernate.generate_statistics=true and a test counting prepared statements (datasource-proxy). Other languages: Django has select_related and prefetch_related; TypeORM has relations and leftJoinAndSelect.
merge, save with assigned ids, and paging with fetch joins
merge(entity)copies the object into a managed instance and returns that; the object you passed stays detached. A common bug: carrying on modifying the old object after merging.- Spring Data's
save()callspersistfor a "new" entity (nullid), otherwisemerge. With app-assigned ids (UUIDs)savealways merges, adding a SELECT before each INSERT. Fix: implementPersistable<ID>or add@Version. - A collection
join fetchwithPageable: Hibernate can't useLIMIT(each parent multiplies into several rows), so it loads everything and pages in memory, warningHHH90003004. Fix: query a page of ids first, then fetch join by id, or use@BatchSize. - Fetch joining two
Lists at once throwsMultipleBagFetchException; switching toSetgives a Cartesian product. Fetch each collection in its own query. @Transactionalon a test keeps the session open, so lazy loading works in tests and throws in production.
4. Working with AI
Hand to AI: query-counting tests for every list endpoint, moving read queries to DTO projections.
Check in AI-written code:
- No
FetchType.EAGER;@ManyToOnestatesLAZYexplicitly. - List endpoints have query-count tests; the count doesn't grow with rows.
- No collection
join fetchtogether withPageable. - No managed entity fields modified just to format a response.
-
spring.jpa.open-in-viewisn't enabled to "fix"LazyInitializationException.
5. Exercises
Exercise 1: Review an "N+1 fix"
The AI fixed N+1 on an admin page with the code below, saying "1 query, with paging". The table has 2 million orders. Find the bug, name the log signature, fix it.
@Query("select o from Order o join fetch o.lines")
Page<Order> findAllWithLines(Pageable pageable);Solution to Exercise 1
A collection fetch join with Pageable: SQL can't apply LIMIT because each order multiplies into several rows. Hibernate loads all 2 million orders with their lines into memory, then cuts the page; the log shows HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory. Small test data runs fine; production runs out of memory.
Fix: the list page only needs totals and status, so page over orders without lines (or a DTO projection). If you need lines: fetch a page of ids first (select o.id from Order o ... with Pageable), then join fetch with where o.id in :ids; or enable default_batch_fetch_size.
Exercise 2: Read a "spontaneous UPDATE" incident
Production logs show thousands of UPDATE courses SET title=?, ... per hour though nobody edits courses. Every title in the DB is now upper case. GET /courses/{id}: a @Transactional service calls course.setTitle(course.getTitle().toUpperCase()) and returns the entity. Diagnose and fix.
Solution to Exercise 2
- Diagnosis:
courseis managed in the transaction. Dirty checking seestitlediffer from the snapshot and issues an UPDATE on commit: a GET endpoint is writing to the DB. - Fix: map to a DTO and format the DTO:
new CourseResponse(c.getId(), c.getTitle().toUpperCase()). Mark read services@Transactional(readOnly = true): Hibernate skips dirty checking and doesn't flush. Run a script to restore titles from a backup or the audit log.
Summary
- The persistence context is a first-level cache: one DB row, one object.
- Modifying a managed entity produces an UPDATE on flush, no
saveneeded. - LAZY by default; fetch deliberately per use case.
- Fix N+1 with fetch joins,
@EntityGraph, batching or DTO projections. - Never
join fetcha collection together withPageable.
Read more: Part 5: JPQL, @Transactional, locking.
Next up: ORM and JPA part 5: JPQL, native queries, @Transactional and locking (open-session-in-view is covered there).
Practice interview questions on this topic
- What are the JPA persistence context and first-level cache? How do they differ from the second-level cache?
- What states can a JPA entity be in? How do persist and merge differ?
- What is dirty checking? How is flush different from commit?
- What is the N+1 query problem, and how do you detect and fix it?
- When does LazyInitializationException occur? What is open-session-in-view and why turn it off?
- How does @EntityGraph differ from JOIN FETCH? What goes wrong when fetching several collections at once?
Comments
Community rules