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?

エンジニア9 分パフォーマンスラボコード課題
javahibernatespring-data-jpasql

この課題はまだ日本語に翻訳されていません。英語版を表示しています。

ミッション:Load one page of 20 orders with at most 3 queries and ≤ 50 ms, without Hibernate paginating in memory.背景 · 学習目標 ▾

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.

ミッション: Load one page of 20 orders with at most 3 queries and ≤ 50 ms, without Hibernate paginating in memory.

学習目標

  • 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.
シミュレーションシミュレーション値

シミュレーションを実行すると出力が表示されます。

シミュレーションを実行
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

簡略化

Fixed round-trip and per-row costs. Real latencies depend on network, indexes and result size. 教育用モデルです。数値は挙動を示すためのもので、ベンチマークではありません。

コンセプト

関連する課題

参考資料