DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk5 min

1 + N Queries for One Feed Page: Find and Fix the N+1 Problem in Spring Boot

A Spring Boot feed can trigger lazy-association queries during mapping or serialization. Find the source, choose a response-matched fetch plan, and validate SQL volume and pagination.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If one Spring Boot feed request issues a query for its page of records and then additional queries for each record’s lazy associations, the likely cause is an N+1 select pattern. Fix it by identifying which associations the response actually needs, choosing an appropriate fetch plan or DTO projection, and checking both SQL volume and page correctness on the versions your application runs.

What the N+1 problem looks like in a feed

A typical feed first selects a page of root entities, such as posts. Code that maps those entities into response objects—or serialization that traverses lazy associations—then triggers more selects to load related data for each root. The request can therefore issue one query for the roots plus repeated association queries. Hibernate describes this as the N+1 selects problem and documents several ways to address it: Hibernate ORM 6.6 introduction.

As an Amazon Associate I earn from qualifying purchases.

The trigger may not be visible in the repository method. A mapper, getter, or JSON serializer can access a lazy association after the repository has returned. Trace the entire request path from repository call through response construction and serialization, and identify which SQL statements belong to that feed request.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How to confirm the pattern before changing the query

  1. Reproduce one representative request. Use enough root records to make repeated association loads visible, and capture SQL in a development or test environment.
  2. Compare query counts at different page sizes. If the number of association selects rises with the number of roots, investigate which property access triggers them. Do not count a pagination count query as an association load: Spring Data JPA notes that pagination may execute a count query as well as the page query. Spring Data JPA query methods
  3. Inspect the SQL and the response work. Record which associations are read, how many rows the database returns, and whether mapping or serialization causes the reads. Spring Data JPA supports query comments for supported generated queries, which may help identify statements in database traces; comments do not measure performance. Spring Data JPA query methods
  4. Keep a correctness baseline. Note the expected number of distinct feed items and the page boundaries, then verify both after changing the fetch plan.

Choose a fetch plan that matches the response

Do not load every association just to suppress extra selects. Decide whether the feed needs full entities, a particular association graph, or only a fixed set of display fields. The right choice depends on the response shape and on the row volume the query produces.

Use an entity graph when returning entities

Spring Data JPA lets a repository method declare the associations to load with @EntityGraph. It supports named graphs and ad hoc graphs through attributePaths. This makes the intended fetch plan visible at the query method without requiring a separate JPQL fetch-join query. Confirm the generated SQL and behavior with your application’s resolved Spring Data JPA and Hibernate versions. Spring Data JPA query methods

Use JOIN FETCH when the join stays manageable

JPQL JOIN FETCH asks Hibernate to retrieve an association in the SQL query for the roots. It can be a clear option when the association and result cardinality suit a join. Hibernate documents join fetching and entity graphs in its ORM 6.6 introduction and ORM 7.0 User Guide.

Be especially careful with to-many collections. A joined result repeats root columns for each child row, increasing row volume and potentially complicating pagination. A query that appears to fetch everything in one round trip can still transfer many rows and hydrate more data than the feed needs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a DTO projection for a fixed feed shape

If a feed needs only fields such as an item’s title and author display name, and does not need a navigable entity graph, a DTO projection can match the response more directly. Hibernate ORM 7 describes DTO projections as an often preferable alternative to batch fetching when the required data can be returned in one query. Hibernate ORM 7.0 User Guide

Use batch fetching as a mitigation, not a complete cure

Batch fetching groups association loads to reduce the number of round trips, but it still uses additional selects rather than planning all required data into one query. Hibernate’s Introduction to Hibernate 6 puts the limitation plainly: “While batch fetching might mitigate problems involving N+1 selects, it won’t solve them.” It can be useful when a join would create a cartesian product or an excessively large result set. Hibernate ORM 6.3 introduction

Can you combine JOIN FETCH with Pageable?

Do not assume that a collection fetch join is a drop-in fix for a paged feed. The join can multiply SQL rows, so pagination and the number of distinct root entities returned may not behave as intended. The reviewed Spring Data and Hibernate references describe fetching and pagination features but do not establish one universal outcome for every association shape, provider version, and dialect. Check the behavior your application actually generates.

For a collection fetch, inspect the SQL limit or offset and verify that the endpoint returns the intended number of distinct roots and correct page boundaries. Test with representative data and the precise Spring Data JPA, Hibernate, and database-dialect versions in the deployed application. Account separately for any count query used to support pagination.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A bounded two-stage design is also worth evaluating for a feed: first page root IDs or projected root data, then retrieve the display associations for only those roots. This avoids treating a collection join as the only way to fetch related data, but it is an application-level design option—not a universal prescription. Validate its page semantics and SQL behavior for your endpoint.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How to tell whether the fix is actually better

Compare the original and revised request using representative data. A lower statement count alone does not prove that the endpoint is faster or correct: a join may return many repeated rows, while a DTO query may avoid unnecessary entity hydration. Evaluate the trade-offs that matter for this feed:

  • Database round trips as page size grows.
  • Rows returned, including repeated root data from joins.
  • Correct page boundaries, distinct-root count, and count-query semantics.
  • Memory use and the amount of entity data hydrated.
  • Fit between the response and a full entity graph versus a bounded DTO.
  • Complexity and maintainability of the repository query.

There is no query-count target that applies to every feed. Use the measurements and correctness assertions for your application, and verify behavior against the exact framework versions and database dialect it runs.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.