The Real Fullstack

The Hibernate N+1 Nightmare

The repository method is one line. Why does the database log show 41 queries for one page?

Ingeniero9 minLaboratorio de rendimientoReto de código
javahibernatespring-data-jpasql

Este reto aún no está traducido al Español. Estás leyendo la versión en inglés.

Misión:Load one page of 20 orders with at most 3 queries and ≤ 50 ms, without Hibernate paginating in memory.Contexto · Objetivos de aprendizaje ▾

Brightcart's back-office lists orders 20 per page with the customer name and item count. The page got slow as data grew. The SQL log shows one query for the orders, then one per order for the customer and one per order for the items.

Misión: Load one page of 20 orders with at most 3 queries and ≤ 50 ms, without Hibernate paginating in memory.

Objetivos de aprendizaje

  • Recognise the N+1 pattern from SQL logs.
  • Know why join fetch and pagination of collections don't mix.
  • Use batch fetching or DTO projections.
SimulaciónSimulado

Ejecuta la simulación para ver la salida.

Ejecutar simulación
Page<Order> page = orders.findAll(PageRequest.of(0, 20));return page.map(o -> new OrderRow(o.getId(),    o.getCustomer().getName(),                       // lazy load: 1 query per order    o.getItems().stream().mapToInt(Item::getQty).sum())); // and another one

Simplificación

Fixed round-trip and per-row costs. Real latencies depend on network, indexes and result size. Modelo educativo: los números ilustran un comportamiento, no son benchmarks.

Conceptos

Retos relacionados

Referencias