SteelReed

Search

Search posts, questions…

JPA & HibernateQuestion 18 / 24

Middle

What is the N+1 query problem, and how do you detect and fix it?

Short answer

N+1 is when 1 query fetches N records, then reading each record's relation fires N more queries: 100 orders become 101 SQL statements. Fix it by fetching everything in one go.

1 query: 100 ordersloop callsorder.getCustomer100 extra SELECTsfix: JOIN FETCH1 statement

3 points to say:

  1. Detect it with SQL logs or query-count tests.
  2. Fix it with JOIN FETCH, @EntityGraph or @BatchSize.
  3. Switching to EAGER does not remove N+1.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.