Menu

Spring Data JPA N+1 queries: find them, fix them, test them
πŸ“°

Spring Data JPA N+1 queries: find them, fix them, test them

DEV Community: javaΒ·duong vuΒ·6 days ago
#yyeOcGK6
#devtojava#devto#dev#hibernate#b1_0
Long article (3261 words) β€” no AI summary yet.
Reading 0:00
15s threshold

Originally published at Shipped Code .

A list endpoint that answers instantly on your laptop can crawl once it meets real data, and the log fills up with near-identical select statements. In Spring Data JPA that is usually the N+1 problem. In the example below, GET /authors returns 10 authors with 3 books each and runs 11 SQL statements. Loading the books in the same query brings it down to 1.

TL;DR. Turn on the org.hibernate.SQL logger and look for 1 query for the list followed by N copies of the same child query. Fix it with left join fetch a.books or @EntityGraph (11 statements become 1), or with hibernate.default_batch_fetch_size , which batches the N queries and leaves paging alone.…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.