# Fix N+1 Queries in a Spring Boot App

Yes. An agent counts Hibernate statements per page in your Spring Boot app, fixes eager loads with entity graphs where the count grows, and adds a count test.

[Run this on Rush](https://cloud.getrush.ai/run/fix-n-plus-one-queries/spring-boot/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the app loads data before it changes a query. In a Spring Boot app like spring-projects/spring-petclinic, `pom.xml` sets `spring-boot-starter-parent` 4.1.0 and `java.version` 17 with the `data-jpa`, `webmvc`, `thymeleaf`, `validation`, `actuator` and `cache` starters, H2 by default plus the MySQL and PostgreSQL drivers, and Testcontainers and `spring-boot-docker-compose` for tests; `build.gradle` mirrors it with the Spring Boot 4.1.0 plugin and a Java 17 toolchain. `application.properties` is the part that matters for query counts: `spring.jpa.open-in-view=false`, so collections must be loaded inside the repository call, `spring.jpa.hibernate.ddl-auto=none` with the schema and seed from `db/${database}/schema.sql` and `data.sql`, and `spring.jpa.properties.hibernate.default_batch_fetch_size=16`, which turns a plain N+1 into one extra statement per 16 entities. `data.sql` seeds 10 owners, 13 pets and 4 visits, which is enough to see the shape but not enough to feel it.

The entities say where the extra statements come from. `Owner.pets` is `@OneToMany(cascade = ALL, fetch = EAGER)` through `owner_id` with `@OrderBy("name")`; `Pet.visits` is `@OneToMany(cascade = ALL, fetch = EAGER)` ordered by date into a `LinkedHashSet`; `Pet.type` is a plain `@ManyToOne`, eager by default; `Vet.specialties` is an eager `@ManyToMany` through `vet_specialties`. `OwnerRepository.findByLastNameStartingWith(String, Pageable)` returns a `Page<Owner>`, and `OwnerController.processFindForm` asks for 5 owners a page, redirects straight to the owner when exactly one matches, and renders `owners/ownersList.html`, which joins `owner.pets` into every row, so each row needs its pets and each pet its type and visits. `ownerDetails.html` iterates `pet.visits` for one owner. `VetRepository.findAll(Pageable)` is `@Cacheable("vets")`, with the cache created in `CacheConfiguration` with statistics on, so the vets page pays once; `PetClinicIntegrationTests.findAll` even calls it twice to show the second is served from cache.

So the agent measures instead of assuming. It runs the app with `logging.level.sql=DEBUG`, the property `PetClinicIntegrationTests` already sets, or turns on `hibernate.generate_statistics` and reads `getPrepareStatementCount()` from the `SessionFactory` statistics after clearing them, and requests `/owners?lastName=` for the list, `/owners/1` for the details and `/vets.html` and `/vets` for the vets. With batch fetching on, a page of 5 owners costs the page query and its count, one `IN` batch for their pets, one batch for the pets' types and one for the visits of up to 16 pets; the count climbs once a page holds more than 16 pets or when the property is removed, which is what the test the agent adds pins down. The fix for the paged list is not a collection fetch join, because Hibernate then paginates in memory and warns about it; the agent adds an `@EntityGraph(attributePaths = {"pets", "pets.type"})` only where it loads a single owner, `findById`, and keeps the batch size for the page, or pages owner ids first and loads the page's owners with their pets in a second query, and says in the pull request which it chose and why.

The test lives with its neighbours. `ClinicServiceTests` is a `@DataJpaTest` with `@AutoConfigureTestDatabase(replace = NONE)` so the MySQL profile reaches a real database, and `OwnerControllerTests` is a `@WebMvcTest` with a `@MockitoBean` repository, which is why it cannot count statements. The agent adds a `@DataJpaTest` beside `ClinicServiceTests` that enables statistics, clears them, calls `findById` and `findByLastNameStartingWith` with a page of 5, and asserts the statement count, and extends `PetClinicIntegrationTests.ownerList` and `ownerDetails`, which already hit the running app on a random port, with the same assertion. Then it runs what `.github/workflows/maven-build.yml` runs, `./mvnw -B verify` on JDK 17, after `./mvnw spring-javaformat:apply`, because the `spring-javaformat-maven-plugin` `validate` goal and the nohttp checkstyle run in the `validate` phase and fail the build on formatting before a single test starts.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Find and fix N+1 queries on this Spring Boot app's main pages. Read pom.xml or build.gradle, application.properties (especially open-in-view, default_batch_fetch_size and ddl-auto) and the entities and repositories under src/main/java first. Start the app on its default database and measure the Hibernate statement count for the owner list, the owner details, the vet list and any other list page, using hibernate.generate_statistics or SQL logging, with enough rows that each list shows several entities. For each page whose count grows with the number of rows, fix it in the repository with an @EntityGraph or a fetch join, never a collection fetch join on a paged query, and keep the batch size setting. Add a @DataJpaTest that enables statistics and asserts the statement count for each repository call you changed, and extend the existing integration test for the pages. Run ./mvnw spring-javaformat:apply and then ./mvnw -B verify, as the Maven workflow does. Do not change the entity fetch types, the schema files or any workflow. Open a pull request that lists each page with its statement count before and after, from your own measurements in this run, and quotes the test summary.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch that changes `OwnerRepository` (an `@EntityGraph` on `findById`, or a two-step page query for `findByLastNameStartingWith`), adds a `@DataJpaTest` beside `ClinicServiceTests` that asserts a statement count per repository call, and extends `PetClinicIntegrationTests` for the pages. The body lists each page with the count the agent measured before and after in its sandbox, and quotes the `./mvnw -B verify` summary, formatting check included.

The session read names the repository and the pull request, and the transcript keeps the SQL log or statistics output for each page before the change, the same after it, the formatter run and the verify run. The `changes` route lists the files with their diff.

Before merging, a reviewer checks that the paged query did not gain a collection fetch join (Hibernate logs a warning when it paginates in memory, and the transcript would show it), that `default_batch_fetch_size` is still set, that the new test's expected counts are explained in a comment so a later schema change can update them with reason, and that the H2 numbers still hold on the profile production uses.

## Run it on every slow-page alert

When your monitoring flags `/owners` or an owner page for latency or statement count, a handler on your server receives the alert and sends this request with the page's URL and the alert's numbers written into `input`, with the repository in `resources` and a `request_id` that is a UUID v5 of the alert id so a repeated notification does not start a second run. A Grafana contact point can call a Rush `webhook` trigger directly, since it can send the `Authorization: Bearer` header the trigger needs; an alerting service that signs its own requests cannot, and goes through your handler instead.

Give the key a `webhook_url` and the end of the turn arrives as `run.completed`, `run.failed` or `run.cancelled`, signed per Standard Webhooks, with `data.session_url` to read for the pull request. One alert, one run, one pull request, each in its own sandbox.

## Why run it on Rush?

Counting statements by hand means starting the app, turning on SQL logging, seeding more than ten owners and reading the log for each page, then doing it again after each change. The agent does that loop in its own sandbox against the project's own H2 or a Postgres started from `docker-compose.yml`, and keeps every count in the transcript rather than in someone's memory.

The pull request proves itself: counts before and after, the formatter and `verify` output, and a test that fails if the count regresses. Several alerts run at once, each in its own sandbox and on its own branch, and a reviewer's follow-up wakes the same sandbox with Maven's dependencies already downloaded.

## Frequently asked questions

### The batch size is already set. Is there anything left to fix?

Often less than a profiler suggests, and the pull request says so when that is the case. Batch fetching caps the damage at one statement per 16 entities per association, so the count still grows with page size and with the number of eager associations; the test the agent adds records the real count so a later change to the entities shows up as a failure rather than a slow page.

### Why not add a fetch join to the paged owner query?

Because a collection fetch join with a `Pageable` makes Hibernate load every matching owner and page in memory, which is worse than the N+1 on a large table. The agent uses a graph only on single-entity loads, or pages ids first and loads the page's owners with their pets in a second query.

### Will it change EAGER to LAZY on the entities?

No. With `open-in-view` off, flipping `Owner.pets` or `Pet.visits` to lazy would break every controller and form that reads them outside a transaction, which is a larger change than an N+1 fix. The prompt keeps the fetch types and moves the loading into the repository methods instead.

### Which database does it measure on?

H2 by default, as `application.properties` and the Maven workflow use. Say `postgres` or `mysql` in the prompt and the agent starts that service from `docker-compose.yml`, runs with that profile, and reports the counts from it, since statement counts do not depend on the engine but query plans do.

## More Spring Boot jobs

- [Turn Sentry Errors Into Fix Pull Requests for a Spring Boot App](https://getrush.ai/run/fix-sentry-errors/spring-boot/)
- [Generate a Typed API Client for a Spring Boot Service](https://getrush.ai/run/generate-api-clients/spring-boot/)
- [Turn GitHub Issues into Pull Requests for a Spring Boot App](https://getrush.ai/run/github-issue-to-pr/spring-boot/)

## The same job on other stacks

- [Fix N+1 Queries in a Flask + SQLAlchemy App](https://getrush.ai/run/fix-n-plus-one-queries/sqlalchemy/)
- [Fix N+1 Queries in a Symfony App](https://getrush.ai/run/fix-n-plus-one-queries/symfony/)
- [Fix N+1 Queries in a Wagtail Site](https://getrush.ai/run/fix-n-plus-one-queries/wagtail/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
