Medium java backend

How do you find and fix an N+1 problem?

The 30 second answer

I look at SQL logs or traces and see one query for the list followed by one query per item, which is the N+1 pattern. I fix it with a fetch join or an entity graph for that use case, or batch fetching so related rows load in groups. Then I add a test that asserts the number of queries, so it does not come back.

I turn on SQL logging or look at traces, and I see one query for the list and then one per row. In Hibernate I fix it per use case with a join fetch or an entity graph, or I set a batch size so it loads associations in one IN query. I keep mappings lazy by default.

Sources (2)
  1. Hibernate 6.6 User Guide: Dynamic fetching (join fetch, entity graphs)
  2. Hibernate 6.6 User Guide: Batch fetching