Performance: N+1 query problem
This affects page load speed by causing many database queries during data fetching, which delays server response and slows down rendering.
Jump into concepts and practice - no test required
List<Order> orders = orderRepository.findAllWithCustomers(); // uses JOIN FETCH or EntityGraph // customers loaded in one query with orders
List<Order> orders = orderRepository.findAll();
for (Order order : orders) {
Customer customer = customerRepository.findById(order.getCustomerId()).orElse(null);
order.setCustomer(customer);
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| N+1 Query Pattern | No direct DOM impact | No direct reflows | Blocks initial paint due to slow server response | [X] Bad |
| Batch Fetching with JOIN FETCH | No direct DOM impact | No direct reflows | Faster initial paint due to quicker server response | [OK] Good |
N+1 query problem in Spring Boot applications?JOIN FETCH in a Spring Data JPA query to avoid the N+1 problem?@Query("SELECT c FROM Customer c")
List<Customer> findAllCustomers();Customer has a lazy-loaded orders collection, what happens when you call findAllCustomers() and then access orders for each customer?List<Author> authors = authorRepository.findAll();
for (Author a : authors) {
System.out.println(a.getBooks().size());
}Post and Comment with a one-to-many lazy relationship. You want to fetch all posts with their comments efficiently. Which approach best avoids the N+1 problem and handles posts with no comments?