Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

This code runs 101 queries for 100 orders:

Java
List<Order> orders = orderRepository.findAll();
orders.forEach(o -> System.out.println(o.getCustomer().getName()));

Explain why and give three ways to fix it.

findAll() runs one query for the orders, and because customer is lazy, each o.getCustomer().getName() runs its own select, so 100 orders cost 1 + 100 queries: the N+1 problem. We fix it with a fetch join such as select o from Order o join fetch o.customer, with @EntityGraph(attributePaths = "customer") on the repository method, or with batch fetching through @BatchSize or hibernate.default_batch_fetch_size; a DTO projection is a fourth option when we only need a few columns.

Why this question is asked

N+1 is the most common performance problem in JPA applications, and it is easy to write by accident because the code looks innocent: one repository call and a loop. On a developer laptop with ten rows it is invisible; in production with 100 rows per page and a network hop to the database, it can add hundreds of milliseconds to every request. Interviewers ask this question to see whether we can recognise the pattern, explain it, and pick the right fix. In this answer, we will see where the 101 queries come from, go through three fixes and a projection, compare them, and finish with a test that keeps the problem from coming back.

1Where the 101 Queries Come From

Order has @ManyToOne(fetch = LAZY) Customer customer. When findAll() runs, Hibernate executes one select on the orders table. For each order, it puts a proxy, a placeholder holding only the customer id, in the customer field. Nothing is loaded yet.

Then the loop calls getName() on each proxy. The proxy has no name, so it asks the session to load that customer, and the session runs select ... from customer where id = ?. That happens once per distinct customer, so with 100 orders from 100 customers we get 100 extra queries. Customers already loaded are reused from the persistence context, so the real number is 1 plus the number of distinct customers, which is still far too many.

Java
List<Order> orders = orderRepository.findAll();
// select ... from orders -- 1
orders.forEach(o -> System.out.println(o.getCustomer().getName()));
// select ... from customer where id = 11 -- 2
// select ... from customer where id = 12 -- 3
// ... one per distinct customer -- up to 101
Step throughThe N+1 pattern
LoopHibernateDatabase
findAll()
select from orders
100 rows
order 1: getCustomer().getName()
select customer 11
order 2: getCustomer().getName()
select customer 12
... 98 more round trips

8 messages in order. Play them, or step through them one at a time.

Each round trip costs network latency, so 100 small queries are far slower than one larger query.

If the association were EAGER, the result would be similar, the selects would just run during findAll() instead of in the loop. So switching to EAGER is not a fix.

2Fix 1: A Fetch Join

A fetch join tells Hibernate to load the association in the same SQL statement and fill the field with real objects instead of proxies.

Java
@Query("select o from Order o join fetch o.customer")
List<Order> findAllWithCustomer();
// select o.*, c.* from orders o join customer c on c.id = o.customer_id -- 1 query

One query, and the loop runs without touching the database. Notice that join fetch is an inner join, so orders without a customer would be dropped; if the association is optional, use left join fetch. The trade-off is that the query is written for this use case, so we may end up with a few variants of the same query.

3Fix 2: An Entity Graph

An entity graph says which associations to load, without writing JPQL. Spring Data applies it to the derived or overridden repository method, and Hibernate generates the join.

Java
interface OrderRepository extends JpaRepository<Order, Long> {
@EntityGraph(attributePaths = "customer")
List<Order> findAll(); // overrides the inherited findAll with a join
}
// select o.*, c.* from orders o left join customer c on c.id = o.customer_id -- 1 query

The SQL is the same idea as a fetch join, usually as a left join. Entity graphs are convenient for derived queries like findByStatus, where writing JPQL would be extra work. But there is a catch: overriding findAll changes it for every caller, so a separate method name such as findAllWithCustomer is often clearer.

4Fix 3: Batch Fetching

Batch fetching keeps the lazy loading but loads several proxies at once. When the first proxy is initialized, Hibernate looks for other uninitialized customer proxies in the session and loads up to N of them in one query with an IN list.

Java
# application.properties: global default
spring.jpa.properties.hibernate.default_batch_fetch_size=50
// or per entity
@Entity @BatchSize(size = 50)
class Customer { ... }
// select ... from orders -- 1
// select ... from customer where id in (11, 12, ..., 60) -- 2
// select ... from customer where id in (61, ..., 110) -- 3

101 queries become 3, and no query had to change, which makes it a good safety net for a whole application. It is still more than one query, and the exact SQL, an IN list or an array parameter on some databases, depends on the Hibernate version.

5A Fourth Option: A DTO Projection

If the loop only prints names, we do not need Order and Customer entities at all. A projection selects exactly the columns the use case needs.

Java
record OrderCustomerName(Long orderId, String customerName) { }
@Query("select new com.shop.OrderCustomerName(o.id, c.name) from Order o join o.customer c")
List<OrderCustomerName> findOrderCustomerNames();
// select o.id, c.name from orders o join customer c on c.id = o.customer_id -- 1 query, 2 columns
Choosing a fix
FixQueries for 100 ordersBest when
Fetch join1a specific use case needs the entities
@EntityGraph1derived query methods, declarative style
Batch fetchingabout 3 with size 50a global safety net, no query changes
DTO projection1, fewer columnsread-only views and reports

This is the fastest option for read-only screens: one query, two columns, nothing tracked in the persistence context. It is not suitable when we need to modify the entities.

6Follow-up questions

How would you write a test that fails if this N+1 returns?

Enable Hibernate statistics in the test with spring.jpa.properties.hibernate.generate_statistics=true, get the Statistics object with entityManagerFactory.unwrap(SessionFactory.class).getStatistics(), call clear(), run the use case, and assert getPrepareStatementCount() equals 1. A library like datasource-proxy can do the same by counting statements at the JDBC level. The test must use enough rows, say 10 orders with different customers, so that an N+1 shows up as 11 instead of 2.

Does join fetch with pagination work?

For a to-one association like customer, yes, because each order still produces one row. For a collection fetch join, Hibernate cannot apply the limit in SQL without cutting collections, so it warns and paginates in memory; there we page the ids first and then fetch the details, or use batch fetching.

Why not just turn on a second-level cache for Customer?

A cache can turn the 100 selects into cache hits, but each is still a lookup, the cache must be kept consistent, and the code still has a hidden per-row access pattern. Fixing the fetch plan is simpler and more predictable; caching is for data read far more often than it changes.

7Conclusion

In this answer, we saw that one query for the orders plus one lazy load per customer gives the N+1 problem, and we fixed it four ways: a fetch join and an entity graph load customers in the same query, batch fetching loads them a batch at a time with no query changes, and a DTO projection selects only the needed columns. A statement-count test keeps the problem from returning.

What to say in the interviewAbout 90 seconds aloud

Open with

This is the N+1 problem. findAll runs one query for the orders, and customer is a lazy @ManyToOne, so each order holds a proxy with only the customer id.

Then, if they want more

In the loop, getName on each proxy makes Hibernate load that customer with its own select, so with 100 orders from different customers we get 101 queries. Each is a network round trip, so it is much slower than one query, even though each one is small. I would fix it in one of three ways.

First, a fetch join, select o from Order o join fetch o.customer, or left join fetch if the customer is optional, which loads everything in one statement. Second, @EntityGraph(attributePaths = "customer") on a repository method, which generates the same join declaratively and fits derived queries.

Third, batch fetching, @BatchSize on Customer or hibernate.default_batch_fetch_size, which keeps laziness but loads customers in IN queries of, say, 50, so 101 queries become 3 without changing any query; I like it as a global safety net. And if the screen only needs names, a DTO projection selecting order id and customer name is the cheapest.

To stop it coming back, I would write a test that enables Hibernate statistics, runs the use case with ten orders, and asserts the prepared statement count.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This code runs 101 queries for 100 orders:": https://scrivio-interview-library.netlify.app/databases/jpa-performance/c33c9bdfa2/