Fetch plans per use case
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
load exactly the data each use case needs.
Planned topics
- Associations should be
LAZYby default; decide the fetch per use case, not on the mapping. JOIN FETCHor an entity graph loads an association in one query; avoids N+1.- Fetching two collections at once creates a cartesian product; fetch one collection and batch the others (
@BatchSizeordefault_batch_fetch_size). - For read-only screens, a DTO projection selects only needed columns and skips the persistence context.
- Pagination with a fetched collection is done in memory by Hibernate (warning
HHH000104); paginate ids first.
Draft outline details
Demonstration
@EntityGraph(attributePaths = "items")
Optional<Order> findWithItemsById(Long id);
@Query("select new com.shop.OrderSummary(o.id, o.total, c.name) from Order o join o.customer c")
List<OrderSummary> summaries();Check your understanding
Why a DTO projection for a list screen?
Show answer
It loads only the needed columns and creates no managed entities.
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.