Pagination with collections
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
avoid fetch-joining a collection with paging.
Planned topics
- A join fetch on a collection multiplies parent rows (one row per child).
- Hibernate cannot page that in SQL, so it loads everything and pages in memory (warning
HHH000104: verify wording for your version). - That can exhaust memory on big tables.
- Safe approach: page the parent ids first, then load children for those ids with a second query.
- Alternative: use
@BatchSizeor a projection.
Draft outline details
Demonstration
Page<Long> ids = orderRepository.findIds(pageable); // page the parents only
List<Order> orders = orderRepository.findWithLinesByIdIn(ids.getContent()); // fetch joinCheck your understanding
Why is join fetch on a collection plus paging dangerous?
Show answer
Paging happens in memory after loading all rows.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.