Video in progress
How do you detect and fix the N+1 problem in a real project?
If the SQL log or Hibernate statistics show a run of identical SELECTs after a single list query, that's N+1. The fix is to load the needed association with join fetch, an entity graph or batch fetching, or to switch to a DTO projection.
📖 Answer
It looks simple: a page shows 50 orders, and the log shows this picture:
select o.* from orders o where o.status = ?
select c.* from customer c where c.id = ? -- 50 times
How I catch it:
- In dev, not
spring.jpa.show-sqlbutlogging.level.org.hibernate.SQL=debug, which makes it easy to count the queries. spring.jpa.properties.hibernate.generate_statistics=truewrites how many JDBC statements were sent at the end of each session.- In tests, assert the query count with datasource-proxy or a similar library: "this endpoint must not send more than 3 queries".
Ways to fix it, depending on the case:
@Query("select o from Order o join fetch o.customer where o.status = :s")
List<Order> findWithCustomer(@Param("s") Status s);
- join fetch: get it in one query; the simplest fix for a
@ManyToOne; @EntityGraph: the same thing, but as an annotation on the repository method;hibernate.default_batch_fetch_size=50: instead of N SELECTs, a few queries withwhere id in (...); especially handy for collections;- DTO projection: if the screen needs only 4 columns, don't load the entity at all.
The key point: making one association EAGER is not a fix. It just moves the problem to other queries.
Sign up to mark studied questions and save your progress.