Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A repository method with @Query("select o from Order o join fetch o.lines") and a Pageable logs 'HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory' and the service uses lots of memory. Explain and fix.

With a collection fetch join, each order comes back as one SQL row per line, so a SQL limit of 20 would cut an order's lines in half. Hibernate therefore drops the limit, loads every matching row and applies the page in memory, which is where the memory goes. We fix it by paging the order ids first and then fetching those orders with their lines by id, or by paging the orders without the fetch join and loading lines with batch fetching, and we give the query a separate count query; Hibernate can also be told to fail instead of paging in memory.

Why this question is asked

This warning looks harmless in the log, but it means the database returns the whole table to the application on every page request. The service seems fine in development with 200 orders and falls over in production with two million. Interviewers ask this because it tests whether we understand how a fetch join becomes SQL rows and why paging and collection fetching do not mix. In this answer, we will recap fetch joins, see exactly why Hibernate pages in memory, and then go through the two-step fix, the batch fetching alternative, the count query and the setting that turns the warning into an error.

1A Quick Recap of Fetch Joins

A fetch join tells Hibernate to load an association in the same SQL query as the entity. select o from Order o join fetch o.lines loads each order and its lines together, which avoids the N+1 problem, one extra query per order to load its lines.

In SQL, a join to a one-to-many collection produces one row per child. An order with three lines comes back as three rows that all repeat the order's columns. Hibernate stitches these rows back into one Order object with a list of three lines.

2Why Hibernate Pages in Memory

Now add a Pageable asking for 20 orders. The natural SQL would be limit 20, but limit counts rows, not orders. If the first order has 15 lines and the second has 10, limit 20 returns the first order complete and the second order with only 5 of its 10 lines. Hibernate would then hand us an order whose collection is silently wrong, which is far worse than slow.

So Hibernate refuses to put the limit in SQL. It runs the query without limit or offset, reads every matching row, builds every order, and then takes the 20 we asked for from the list in memory. It logs HHH90003004 to say so.

Java
@Query("select o from Order o join fetch o.lines")
Page<Order> findAllWithLines(Pageable pageable);
// SQL actually sent: no limit, no offset
// select o.*, l.* from orders o join order_lines l on l.order_id = o.id order by ...
// WARN HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory
Why a SQL limit would cut an order
SQL roworder_idline_idIn limit 20?
1 to 151lines 1 to 15Yes
16 to 202lines 1 to 5Yes
21 to 252lines 6 to 10No: order 2 would be incomplete
A row limit counts lines, not orders, so Hibernate cannot use it.

With two million orders averaging five lines each, every page request reads ten million rows and builds two million Order objects to return 20. That explains the memory, and also the slow responses and the garbage collection pauses that usually come with it.

3Fix 1: Page the Ids, Then Fetch by Id

The cleanest fix splits the work into two queries. The first selects only order ids, with the ordering and the limit, which is a normal paged query with one row per order. The second loads those orders with their lines using where o.id in :ids. Because the second query has no limit, it can fetch the collection safely, and because it only asks for 20 orders, it is small.

Java
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query(value = "select o.id from Order o",
countQuery = "select count(o) from Order o")
Page<Long> findPageOfIds(Pageable pageable); // limit and offset in SQL
@Query("select o from Order o join fetch o.lines where o.id in :ids")
List<Order> findWithLines(@Param("ids") List<Long> ids);
}
@Transactional(readOnly = true)
public Page<Order> page(Pageable pageable) {
Page<Long> ids = repo.findPageOfIds(pageable); // 20 ids, e.g. [905, 904, ...]
Map<Long, Order> byId = repo.findWithLines(ids.getContent()).stream()
.collect(Collectors.toMap(Order::getId, o -> o)); // 20 orders, lines complete
List<Order> ordered = ids.getContent().stream().map(byId::get).toList();
return new PageImpl<>(ordered, pageable, ids.getTotalElements());
}
Step throughTwo-step paging
ServiceHibernateDatabase
findPageOfIds(page 3, size 20)
select id ... order by ... limit 20 offset 60
20 ids
select count(*) from orders
findWithLines(20 ids)
select o, l ... where o.id in (...)
about 100 rows: 20 orders with lines

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

Only the rows for one page cross the wire.

Notice two details. An in clause does not preserve order, so we put the orders back in the order of the id page. And Hibernate 6 removes duplicate roots from fetch join results automatically, so we no longer need distinct for that purpose. The sort in the Pageable must include a unique tiebreaker such as id so the id pages are stable.

4Fix 2: Page Without the Fetch, Batch the Lines

A simpler alternative is to remove the fetch join, page the orders normally, and let Hibernate load the lines lazily, but in batches. With batch fetching, when the code touches the first order's lines, Hibernate loads the lines of up to N orders already in the persistence context in one query, using an in clause.

Java
@Entity
class Order {
@OneToMany(mappedBy = "order")
@BatchSize(size = 20) // or spring.jpa.properties.hibernate.default_batch_fetch_size=20
private List<OrderLine> lines;
}
Page<Order> page = repo.findAll(PageRequest.of(3, 20, Sort.by("createdAt", "id")));
page.getContent().get(0).getLines().size(); // one query loads lines for all 20 orders

So a page costs three queries, the page, the count and one batch of lines, instead of 22. This fix needs fewer code changes, but the lines are loaded on first access, so it must happen inside the transaction or the open session.

5Give It a Separate Count Query and Make the Warning an Error

The count for a fetch join query must not contain the fetch, so we always provide countQuery explicitly, as in the first fix, counting the root entity only.

To stop this from happening again, Hibernate has a setting that turns the warning into an exception, so the problem fails in tests instead of eating memory in production.

Properties
# application.properties
spring.jpa.properties.hibernate.query.fail_on_pagination_over_collection_fetch=true
# a paged collection fetch now throws instead of loading everything

6Follow-up questions

Why does a fetch join on a many-to-one not cause this?

A to-one association, such as order.customer, adds columns to each order row but does not multiply rows. One order is still one row, so a SQL limit counts orders correctly and Hibernate applies it in SQL. Only collection fetches, one-to-many and many-to-many, cause in-memory paging.

Would an entity graph avoid the problem?

No. An entity graph that loads a collection produces the same join and the same row multiplication, so Hibernate pages in memory for the same reason. Entity graphs help in the second step of the two-step approach, for the query by ids.

Is the two-step approach worth it over batch fetching?

Batch fetching is simpler and usually good enough. The two-step approach gives us full control over what the second query loads, for example several collections in separate queries, and keeps everything inside one service method, which helps when the entities leave the transaction afterwards.

7Conclusion

In this answer, we saw that combining a collection fetch join with paging forces Hibernate to load every matching row and page in memory, because a SQL row limit would cut an order's collection. We fixed it by paging ids first and fetching orders with lines by id, or by paging without the fetch and using batch fetching, gave the query a separate count query without the fetch, and enabled fail_on_pagination_over_collection_fetch so the mistake fails fast.

What to say in the interviewAbout 80 seconds aloud

Open with

The warning means Hibernate is paging in memory. With join fetch o.lines, an order comes back as one row per line, so a SQL limit of 20 would count lines, not orders, and could cut an order's lines in half.

Then, if they want more

Rather than return incomplete collections, Hibernate sends the query with no limit at all, loads every order and every line, and takes the 20 in memory. With millions of orders that explains the memory use. My preferred fix is two queries.

First a paged query that selects only order ids, ordered with a unique tiebreaker and limited in SQL, with its own count query. Then a second query that fetches those orders with join fetch where id in the list, which is safe because it has no limit, and I restore the order of the ids in Java.

The simpler alternative is to drop the fetch join, page the orders normally and put @BatchSize or default_batch_fetch_size on the collection, so all lines for the page load in one extra query. Either way the count query must not contain the fetch. And I would set hibernate.query.fail_on_pagination_over_collection_fetch to true so this fails in tests instead of production.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
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 "A repository method with @Query("select o from Order o join fetch o.lines") and a...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/34d363bc5e/