spring data jpa / sql / query performance·7 min read

silent spring data jpa performance killers and how to fix them

recognize n+1 queries, early materialization, unnecessary persistence context work, growing joins and deep pagination through an order list you can run locally.

an order list is instant during development. months later it becomes slow while still returning correct results. small data can hide growing work. investigate how often the application visits the database, how much it transfers and which parts the screen actually needs.

published: updated:

replace n+1 with projection, unbounded reads with filtered pages of 20 rows and large graphs with required fields. measure correctness and resource use.
in this article

define the work before measuring it

our screen needs 20 order ids, customer names and line counts. payment history and complete customer records are outside that contract. this gives us a concrete reason to reduce the query.

compare endpoint duration, executed command count, transferred data and allocations using the same dataset. separate first execution from warm runs; compare repeated measurements using median and p95 rather than a single stopwatch reading.

repeat with representative volume and your target database provider. the numbers below illustrate query behavior; they are not measured speedup claims.

n+1: a small query repeated many times

load 20 orders and access each customer inside a loop: that is 21 database trips. jpa loads relationships lazily by default, so every access in the loop can trigger another statement. network waiting accumulates even if each query is quick.

project customer name and item count in a jpql projection when the screen only needs those values. a translatable expression allows the database to provide them without loading the entire relationship graph. the following query needs no entity fetch at all.

a loop alone does not prove n+1. related data may already be loaded or fetched with a join. count the commands executed during the request.

materializing too early

repository.findAll() executes the query and loads every order into memory. a filter applied afterwards runs in java instead of the database. displaying 20 rows does not undo the cost of loading every order.

in the improved query, filtering, ordering and projection precede execution. afterId is the last order id from the previous page and pageRequest carries the limit and ordering. the interface projection follows spring data’s interface projection approach: the result contains the requested fields instead of a managed entity.

use slice instead of page when the total count is not displayed. page runs an additional count query on every request. on large tables that query can cost more than the list itself. spring data’s hibernate.generate_statistics setting can be enabled in development to count the executed commands.

OrderRepository.java · java 25 / spring data jpa
// Bad: load every order before filtering.
List<Order> all = orderRepository.findAll();
List<Order> page = all.stream()
        .filter(order -> order.getId() > afterId)
        .limit(20)
        .toList();

// Better: filter, order and project in SQL.
List<OrderSummary> rows = orderRepository.findSummaries(afterId, PageRequest.of(0, 20));

// The projection is computed by the database and returns no managed entity.
interface OrderSummary {
    Long getId();
    String getCustomerName();
    Long getLineCount();
}

do not manage objects you will not change

jpa keeps loaded entities in the persistence context and tracks their changes for the duration of the transaction. for a large read-only list that work is unnecessary. @Transactional(readOnly = true) removes flush and dirty checking overhead, but the projection above returns no entity at all, so there is nothing to track.

a projection never loads an entity, so the persistence context stays empty. a class based projection maps the required fields and keeps entities out of the service layer.

calling entityManager.clear() is not a performance strategy; it only drops objects from memory. change tracking is useful for data you will write. instead of disabling it across the application, separate read and write needs at the query level.

one query can still move too much data

an order with 10 items and 3 payments can produce 30 joined rows when both sibling collections are fetched. reconstructing the object graph does not erase database and network work.

when a detail screen really needs both collections, consider the @EntityGraph option. combining a collection fetch with pagination makes hibernate load the rows into memory and log a warning. spring boot 4 can make that risk explicit with the hibernate.query.fail_on_pagination_over_collection_fetch setting.

fetching two list-typed collections at once raises a multiplebagfetchexception; using set-typed collections removes that risk. data may change between separate queries. if a consistent snapshot is required, evaluate suitable transaction isolation and its costs.

a detail screen that needs collections
// A detail screen that really needs both collections:
@EntityGraph(attributePaths = {"items", "payments"})
Optional<Order> findWithCollectionsById(Long id);

// A list screen that only needs a count should not load the graph at all.
@Query("select size(o.items) from Order o where o.id = :id")
long countItems(@Param("id") Long id);

deep pages and suitable indexes

an offset based request for page 5000 requires the database to read and discard the earlier rows. for next-page navigation, keyset pagination carries the last observed key. id > afterId and order by id implement that here. id order is a deliberate choice and does not promise creation-time order.

date ordering needs a unique tie breaker such as id. include both in the cursor and ordering. keyset navigation alone does not implement a direct jump to page 57.

inspect the execution plan for an index matching the filter and ordering. indexes also cost storage and writes. a customer filter combined with id ordering may justify a composite index; verify with the real plan. apply authorization or tenant filters before paging in a real system.

running asynchronously does not repair expensive sql

an @Async method helps avoid occupying an application thread while waiting for the database. it does not reduce query work: the query still takes the same time, only the calling thread is released.

the entitymanager is not thread safe. pass projections or dtos across thread boundaries instead of shared entities. spring data repositories are thread safe for queries, but the persistence context is not: each transaction manages its own.

for bulk updates, use @Modifying with @Query instead of loading entities. managing many records one by one in a single transaction costs considerably more memory and time than a single bulk statement.

run a local demonstration

create a project with spring initializr, choosing “spring boot”, “java 25”, “spring data jpa”, “h2 database” and “postgresql”, then run “mvn spring-boot:run”. add the repository and application class below and point the datasource at h2.

the program uses an in-memory h2 database and seeds 100 orders on its first run. with fresh data, expect ids 1–20, customer Ada and two items per order. because the projection returns no entity, the number of tracked entities in the persistence context stays at zero.

this h2 demo does not establish postgresql performance. ddl-auto: create-drop is demo initialization rather than a production schema strategy. real projects use flyway or liquibase so that database changes are versioned and reviewable.

QueryDemoApplication.java · java 25 / spring data jpa / h2
package com.example.querydemo;

import java.util.List;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

@SpringBootApplication
public class QueryDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(QueryDemoApplication.class, args);
    }

    @Bean
    CommandLineRunner seed(OrderRepository orders) {
        return args -> {
            if (orders.count() > 0) {
                return;
            }
            Customer customer = new Customer("Ada");
            for (int i = 0; i < 100; i++) {
                Order order = new Order(customer);
                order.addItem(new OrderItem());
                order.addItem(new OrderItem());
                customer.getOrders().add(order);
            }
            orders.saveAll(customer.getOrders());
        };
    }
}

interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("""
            select o.id as id,
                   o.customer.name as customerName,
                   size(o.items) as lineCount
            from Order o
            where o.id > :afterId
            order by o.id
            """)
    List<OrderSummary> findSummaries(@Param("afterId") long afterId, PageRequest pageable);
}

interface OrderSummary {
    Long getId();
    String getCustomerName();
    Long getLineCount();
}

prove both correctness and improvement

compare order ids, customer names and counts before measuring performance. exclude schema creation and seed commands from the list-query measurement. set afterId to 20 and expect ids 21–40.

exercise empty results and the final page. h2 cannot prove relational query performance on its own. inspect plans and p95 latency under representative concurrent load on the actual provider.

record data volume, provider and package versions, code revision and measurement conditions. reduced transfers and allocations can reduce resource consumption; do not claim a carbon savings percentage without measuring it.

application.yml · h2 / hibernate statistics
spring:
  datasource:
    url: jdbc:h2:mem:shop;MODE=PostgreSQL
    username: sa
    password:
  jpa:
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        format_sql: true
        generate_statistics: true

frequently asked questions

how do i detect an n+1 problem in spring data jpa?
measure first: how many sql statements does a list screen run and how many rows does it move? a query count far above the expectation usually means lazy loading. bring the relationships back with a fetch join or an interface projection so they arrive in one query or in a smaller result set, then measure the query count again.
how should pagination and deep offsets be handled?
offset pagination reads and discards the skipped rows, so deep pages get more expensive. keep the page size small and add indexes that match the sort columns. for very large lists, keyset pagination continues from the last key instead of skipping rows, which keeps the cost predictable.
how do i prove a jpa performance improvement?
prove correctness first and the improvement second. run the same scenario and show that the returned rows are identical, that the query count fell and that the response time shortened. measure the change in an isolated environment, and check the query count as well before claiming that the timing alone improved.
thanks for reading← all articles

help applying this to your project

explore code review, bug fixes and performance consulting for your existing java and spring boot application.

java & spring boot consulting