Performance: Join fetch for optimization
This affects the database query performance and the time it takes to load related data in the application, impacting page load speed and responsiveness.
Jump into concepts and practice - no test required
List<Order> orders = entityManager.createQuery("SELECT o FROM Order o JOIN FETCH o.items", Order.class).getResultList();
List<Order> orders = entityManager.createQuery("SELECT o FROM Order o", Order.class).getResultList(); for (Order order : orders) { order.getItems().size(); // triggers separate query per order }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Without join fetch (N+1 queries) | N+1 database queries | Multiple server response delays | Slower initial paint due to delayed data | [X] Bad |
| With join fetch (single query) | Single database query | Faster server response | Faster initial paint with data ready | [OK] Good |
JOIN FETCH in Spring Boot JPA queries?JOIN FETCH doesJOIN FETCH tells JPA to load related entities eagerly in the same query instead of lazy loading them later.JOIN FETCH before the association path: JOIN FETCH p.children.SELECT p FROM Parent p JOIN FETCH p.children matches the correct syntax. The others misuse the order of keywords or use incorrect join types.SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id
JOIN FETCH to eagerly load the items collection along with the Order entity filtered by id.SELECT c FROM Customer c JOIN FETCH c.orders o WHERE o.status = 'PENDING'
orders with WHERE o.status = 'PENDING' can cause multiple rows per customer if they have multiple pending orders.Customer entities in the result list unless distinct is used.Author entities with their books and each book's publisher in one query. Which JPQL query correctly uses join fetch for this?JOIN FETCH a.books b and then JOIN FETCH b.publisher to fetch nested associations.