Spring Data JPA: fetch plans, projections and scrolling
Most slow JPA code is slow because it runs too many queries or reads too many columns, not because a single query is slow. This page counts the SQL statements behind common repository calls, compares the ways to load associations, and shows how projections and keyset scrolling read only what a screen needs.
Contents
Why JPA code runs more queries than you wrote The N+1 problem, counted Fixing it: JOIN FETCH, @EntityGraph and @BatchSize Fetching two collections at once Paging when a collection is fetched Projections: reading only what you need Keyset scrolling with Window Finding these problems early Choosing a fetch strategy
Why JPA code runs more queries than you wrote
With JPA you ask for entities, and Hibernate decides which SQL statements to run. For a single entity that is simple. For entities with associations, Hibernate has to decide when to load the related rows, and its default for collections is "as late as possible": a @OneToMany
That default is a good one, because most screens do not need every association. But it means a loop over 100 orders that reads each order's lines runs 101 queries: one for the orders and one per order for its lines. This is the N+1 problem, and it rarely shows up in tests with three rows of data.
The tools for controlling what is loaded, and when, fall into two groups: changing the fetch plan of entity queries, and not loading entities at all.
| Tool | What it does | Best for |
|---|---|---|
JOIN FETCH | Loads the association in the same SQL query with a join | One query method that always needs the association |
@EntityGraph | Same join, declared on a repository method by attribute names | Derived query methods, without writing JPQL |
@BatchSizehibernate.default_batch_fetch_size | Loads lazy collections for many parents at once with IN (...) | A safety net for code that walks associations |
| Interface or record projections | Selects only some columns, returns no entities | Read-only lists and API responses |
WindowScrollPosition | Keyset scrolling: "rows after this key" instead of an offset | Large tables and batch processing |
The examples run Spring Boot 4.1 with Spring Data JPA 4.1 and Hibernate 7.4 on H2. To count statements, they switch on Hibernate's statistics with spring.jpa.properties.hibernate.generate_statistics=trueStatistics.getPrepareStatementCount()drop
The N+1 problem, counted
Three authors with two books each are enough to see the pattern. The program prints each author's book count, which reads every books
package adv.nplusone;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.stat.Statistics;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.support.TransactionTemplate;
@SpringBootApplication
public class NPlusOne {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(NPlusOne.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"logging.pattern.console", "%logger{0}: %msg%n",
"spring.jpa.properties.hibernate.generate_statistics", "true"));
try (var context = app.run(args)) {
LoggingSystem.get(NPlusOne.class.getClassLoader())
.setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
AuthorRepository authors = context.getBean(AuthorRepository.class);
TransactionTemplate tx = context.getBean(TransactionTemplate.class);
for (String name : List.of("Austen", "Herbert", "Tolkien")) {
Author author = new Author(name);
author.addBook(name + " book 1");
author.addBook(name + " book 2");
authors.save(author);
}
Statistics stats = context.getBean(EntityManagerFactory.class)
.unwrap(SessionFactory.class).getStatistics();
stats.clear();
System.out.println("--- print every author with their book count");
tx.executeWithoutResult(status -> {
for (Author author : authors.findAll()) {
System.out.println(author.getName() + ": " + author.getBooks().size());
}
});
System.out.println("SQL statements: " + stats.getPrepareStatementCount());
System.out.println("Collections loaded one by one: "
+ stats.getCollectionFetchCount());
}
}
}
@Entity
class Author {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<Book> books = new ArrayList<>();
protected Author() {
}
Author(String name) {
this.name = name;
}
void addBook(String title) {
books.add(new Book(title, this));
}
String getName() {
return name;
}
List<Book> getBooks() {
return books;
}
}
@Entity
class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne
private Author author;
protected Book() {
}
Book(String title, Author author) {
this.title = title;
this.author = author;
}
String getTitle() {
return title;
}
}
interface AuthorRepository extends JpaRepository<Author, Long> {
}
SQL: select next value for author_seq
SQL: select next value for book_seq
SQL: select next value for book_seq
SQL: insert into author (name,id) values (?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: select next value for author_seq
SQL: insert into author (name,id) values (?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into author (name,id) values (?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
--- print every author with their book count
SQL: select a1_0.id,a1_0.name from author a1_0
SQL: select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?
Austen: 2
SQL: select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?
Herbert: 2
SQL: select b1_0.author_id,b1_0.id,b1_0.title from book b1_0 where b1_0.author_id=?
Tolkien: 2
SQL statements: 4
Collections loaded one by one: 3
SQL: drop table if exists author cascade
SQL: drop table if exists book cascade
SQL: drop sequence if exists author_seq
SQL: drop sequence if exists book_seq
ran one query for the three authors. It did not touch thefindAll() table.book- Each call to
then ran its owngetBooks().size() , interleaved with the printing. Hibernate loaded the collections one by one, as the statistics confirm: 3 collection fetches.select ... from book where author_id=? - That makes 4 statements for 3 authors: N+1, with N = 3. With 500 authors on a page it would be 501 round trips to the database.
The loop must run inside a transaction for lazy loading to work at all. Outside one, the first getBooks()LazyInitializationExceptionFetchType.EAGERfindAll()
Fixing it: JOIN FETCH, @EntityGraph and @BatchSize
This program loads 20 authors, each with two books, in three ways, and 20 shelves with one item each using batch fetching. Each run counts the statements it needed:
package adv.fetch;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.BatchSize;
import org.hibernate.stat.Statistics;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.support.TransactionTemplate;
@SpringBootApplication
public class FetchStrategies {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(FetchStrategies.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"spring.jpa.properties.hibernate.generate_statistics", "true"));
try (var context = app.run(args)) {
AuthorRepository authors = context.getBean(AuthorRepository.class);
ShelfRepository shelves = context.getBean(ShelfRepository.class);
TransactionTemplate tx = context.getBean(TransactionTemplate.class);
for (int i = 1; i <= 20; i++) {
Author author = new Author("Author " + i);
author.addBook("Book " + i + "a");
author.addBook("Book " + i + "b");
authors.save(author);
Shelf shelf = new Shelf("Shelf " + i);
shelf.addItem("Item " + i);
shelves.save(shelf);
}
Statistics stats = context.getBean(EntityManagerFactory.class)
.unwrap(SessionFactory.class).getStatistics();
run("findAll() (lazy, N+1)", stats, tx, () -> totalBooks(authors.findAll()));
run("JOIN FETCH query", stats, tx, () -> totalBooks(authors.findAllWithBooks()));
run("@EntityGraph", stats, tx, () -> totalBooks(authors.findAllBy()));
run("@BatchSize(size = 8)", stats, tx, () -> {
List<Shelf> all = shelves.findAll();
return all.size() + " shelves, "
+ all.stream().mapToInt(s -> s.getItems().size()).sum() + " items";
});
}
}
static String totalBooks(List<Author> list) {
return list.size() + " authors, "
+ list.stream().mapToInt(a -> a.getBooks().size()).sum() + " books";
}
static void run(String label, Statistics stats, TransactionTemplate tx,
Supplier<String> work) {
stats.clear();
String result = tx.execute(status -> work.get());
System.out.printf("%-24s %-22s SQL statements: %d%n",
label, result, stats.getPrepareStatementCount());
}
}
@Entity
class Author {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<Book> books = new ArrayList<>();
protected Author() {
}
Author(String name) {
this.name = name;
}
void addBook(String title) {
books.add(new Book(title, this));
}
List<Book> getBooks() {
return books;
}
}
@Entity
class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne
private Author author;
protected Book() {
}
Book(String title, Author author) {
this.title = title;
this.author = author;
}
}
@Entity
class Shelf {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "shelf", cascade = CascadeType.ALL)
@BatchSize(size = 8)
private List<Item> items = new ArrayList<>();
protected Shelf() {
}
Shelf(String name) {
this.name = name;
}
void addItem(String label) {
items.add(new Item(label, this));
}
List<Item> getItems() {
return items;
}
}
@Entity
class Item {
@Id
@GeneratedValue
private Long id;
private String label;
@ManyToOne
private Shelf shelf;
protected Item() {
}
Item(String label, Shelf shelf) {
this.label = label;
this.shelf = shelf;
}
}
interface AuthorRepository extends JpaRepository<Author, Long> {
@Query("select a from Author a join fetch a.books")
List<Author> findAllWithBooks();
@EntityGraph(attributePaths = "books")
List<Author> findAllBy();
}
interface ShelfRepository extends JpaRepository<Shelf, Long> {
}
findAll() (lazy, N+1) 20 authors, 40 books SQL statements: 21
JOIN FETCH query 20 authors, 40 books SQL statements: 1
@EntityGraph 20 authors, 40 books SQL statements: 1
@BatchSize(size = 8) 20 shelves, 20 items SQL statements: 4
- The plain
needed 21 statements: 1 for the authors and 20 for the collections.findAll() - The
query needed 1. The join returns 40 rows, one per book, but the result has 20 authors, not 40. Since Hibernate 6, duplicate parents from a fetch join are removed automatically; with Hibernate 5 the query neededJOIN FETCH .select distinct on@EntityGraph(attributePaths = "books") produced the same single query without any JPQL.findAllBy() is a derived query with no conditions; it exists only to carry the annotation.findAllBy kept the collection lazy, but when the first shelf's items were read, Hibernate loaded the items of up to 8 shelves in one@BatchSize(size = 8) query. 20 shelves need 1 query for the shelves and 3 for the items (8, 8 and 4), so 4 in all.IN
Fetch joins and entity graphs are exact: they load what one use case needs. Batch fetching is the general safety net: setting spring.jpa.properties.hibernate.default_batch_fetch_size=16
Fetching two collections at once
Joining one collection multiplies the rows by its size. Joining two multiplies them by both sizes, which Hibernate refuses for some collection types. This author has three books and three awards, mapped once as a ListSet
package adv.bags;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.support.TransactionTemplate;
@SpringBootApplication
public class MultipleBags {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MultipleBags.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "OFF"));
try (var context = app.run(args)) {
AuthorRepository authors = context.getBean(AuthorRepository.class);
TransactionTemplate tx = context.getBean(TransactionTemplate.class);
Author author = new Author("Austen");
for (int i = 1; i <= 3; i++) {
author.books.add(new Book("Book " + i, author));
author.awards.add(new Award("Award " + i, author));
}
authors.save(author);
try {
tx.executeWithoutResult(status -> authors.findWithBothListsBy());
} catch (RuntimeException e) {
Throwable cause = e;
while (cause.getCause() != null) {
cause = cause.getCause();
}
System.out.println("Two List collections: " + cause.getClass().getSimpleName());
System.out.println(" " + cause.getMessage());
}
tx.executeWithoutResult(status -> {
Author loaded = authors.findWithListAndSetBy().get(0);
System.out.println("List + Set: " + loaded.books.size() + " books, "
+ loaded.awardSet.size() + " awards");
});
}
}
}
@Entity
class Author {
@Id
@GeneratedValue
Long id;
String name;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
List<Book> books = new ArrayList<>();
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
List<Award> awards = new ArrayList<>();
@OneToMany(mappedBy = "author")
Set<Award> awardSet = new LinkedHashSet<>();
protected Author() {
}
Author(String name) {
this.name = name;
}
}
@Entity
class Book {
@Id
@GeneratedValue
Long id;
String title;
@ManyToOne
Author author;
protected Book() {
}
Book(String title, Author author) {
this.title = title;
this.author = author;
}
}
@Entity
class Award {
@Id
@GeneratedValue
Long id;
String title;
@ManyToOne
Author author;
protected Award() {
}
Award(String title, Author author) {
this.title = title;
this.author = author;
}
}
interface AuthorRepository extends JpaRepository<Author, Long> {
@EntityGraph(attributePaths = {"books", "awards"})
List<Author> findWithBothListsBy();
@EntityGraph(attributePaths = {"books", "awardSet"})
List<Author> findWithListAndSetBy();
}
Two List collections: MultipleBagFetchException
cannot simultaneously fetch multiple bags: [adv.bags.Author.awards, adv.bags.Author.books]
List + Set: 9 books, 3 awards
- Fetching two
collections failed withList . Hibernate calls aMultipleBagFetchException without an order column a bag, a collection that may hold duplicates. From the 9 rows of the join (3 books times 3 awards), it cannot tell which duplicates are real.List - With the awards as a
the query ran, and that is the second trap: the author now has 9 books, not 3. Each book appeared once per award in the joined rows, and the bag kept every copy. TheSet of awards removed its own duplicates, so it has the right count of 3.Set
Two fixes work well: make both collections a Set
Paging when a collection is fetched
A page of authors with their books is a common request, and it combines a limit with a join that multiplies rows. With five authors of two books each, the limit has to apply to authors, not to the 10 joined rows:
package adv.pagetrap;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.support.TransactionTemplate;
@SpringBootApplication
public class PagedFetch {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(PagedFetch.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"logging.pattern.console", "%logger{0}: %msg%n"));
try (var context = app.run(args)) {
LoggingSystem.get(PagedFetch.class.getClassLoader())
.setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
AuthorRepository authors = context.getBean(AuthorRepository.class);
TransactionTemplate tx = context.getBean(TransactionTemplate.class);
for (int i = 1; i <= 5; i++) {
Author author = new Author("Author " + i);
author.addBook("Book " + i + "a");
author.addBook("Book " + i + "b");
authors.save(author);
}
System.out.println("--- page of authors with books fetched in the same query");
tx.executeWithoutResult(status -> {
Page<Author> page = authors.findAllBy(PageRequest.of(0, 2, Sort.by("id")));
System.out.println("Got " + names(page.getContent()) + " of "
+ page.getTotalElements() + ", books: " + books(page.getContent()));
});
System.out.println("--- two queries: page the ids, then fetch those authors");
tx.executeWithoutResult(status -> {
Page<Long> ids = authors.findPageOfIds(PageRequest.of(0, 2));
List<Author> page = authors.findWithBooksByIdIn(ids.getContent());
System.out.println("Got " + names(page) + " of " + ids.getTotalElements()
+ ", books: " + books(page));
});
}
}
static List<String> names(List<Author> authors) {
return authors.stream().map(Author::getName).toList();
}
static int books(List<Author> authors) {
return authors.stream().mapToInt(a -> a.getBooks().size()).sum();
}
}
@Entity
class Author {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<Book> books = new ArrayList<>();
protected Author() {
}
Author(String name) {
this.name = name;
}
void addBook(String title) {
books.add(new Book(title, this));
}
String getName() {
return name;
}
List<Book> getBooks() {
return books;
}
}
@Entity
class Book {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToOne
private Author author;
protected Book() {
}
Book(String title, Author author) {
this.title = title;
this.author = author;
}
}
interface AuthorRepository extends JpaRepository<Author, Long> {
@EntityGraph(attributePaths = "books")
Page<Author> findAllBy(Pageable pageable);
@Query(value = "select a.id from Author a order by a.id",
countQuery = "select count(a) from Author a")
Page<Long> findPageOfIds(Pageable pageable);
@EntityGraph(attributePaths = "books")
List<Author> findWithBooksByIdIn(List<Long> ids);
}
SQL: select next value for author_seq
SQL: select next value for book_seq
SQL: select next value for book_seq
SQL: insert into author (name,id) values (?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: select next value for author_seq
SQL: insert into author (name,id) values (?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into author (name,id) values (?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into author (name,id) values (?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into author (name,id) values (?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
SQL: insert into book (author_id,title,id) values (?,?,?)
--- page of authors with books fetched in the same query
SQL: select a1_0.id,b1_0.author_id,b1_0.id,b1_0.title,a1_0.name from (select a1_0.id,a1_0.name from author a1_0 order by a1_0.id offset ? rows fetch first ? rows only) a1_0(id,name) left join book b1_0 on a1_0.id=b1_0.author_id order by a1_0.id
SQL: select count(*) from author a1_0
Got [Author 1, Author 2] of 5, books: 4
--- two queries: page the ids, then fetch those authors
SQL: select a1_0.id from author a1_0 order by a1_0.id fetch first ? rows only
SQL: select count(a1_0.id) from author a1_0
SQL: select a1_0.id,b1_0.author_id,b1_0.id,b1_0.title,a1_0.name from author a1_0 left join book b1_0 on a1_0.id=b1_0.author_id where a1_0.id in (?,?)
Got [Author 1, Author 2] of 5, books: 4
SQL: drop table if exists author cascade
SQL: drop table if exists book cascade
SQL: drop sequence if exists author_seq
SQL: drop sequence if exists book_seq
- Hibernate 7.4 handled the entity graph with a page correctly in SQL. It put the
andoffset limit inside a subquery that selects authors, then joined the books to those two authors. The page holds Author 1 and Author 2 with all 4 of their books.fetch first - The sort by id appears twice, inside the subquery and outside it. Without a
, the subquery would pick two authors in whatever order the database returns them.Sort - The second approach pages over ids only, then loads those authors with their books using
. It needs three statements instead of two, but each one is simple, and it works the same way with every JPA provider and version.id in (?,?)
Older Hibernate versions, including the Hibernate 6 used by Spring Boot 3, do not rewrite this query. They load every matching row, apply the page in memory, and log the warning HHH90003004: firstResult/maxResults specified with collection fetch; applying in memoryhibernate.query.fail_on_pagination_over_collection_fetch=true
Projections: reading only what you need
When the result is only displayed or returned as JSON, entities are more than you need: Hibernate tracks every loaded entity for dirty checking, and the query reads every column. A projection asks for a few columns and returns plain objects. The product table has a long description
package adv.projections;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@SpringBootApplication
public class Projections {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Projections.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"logging.pattern.console", "%logger{0}: %msg%n"));
try (var context = app.run(args)) {
LoggingSystem.get(Projections.class.getClassLoader())
.setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
ProductRepository products = context.getBean(ProductRepository.class);
products.saveAll(List.of(
new Product("Desk", "furniture", "199.00", "Oak desk, 140 cm"),
new Product("Chair", "furniture", "89.50", "Mesh office chair"),
new Product("Lamp", "lighting", "24.99", "LED desk lamp")));
System.out.println("--- interface projection");
for (NameAndPrice p : products.findByCategory("furniture")) {
System.out.println(p.getName() + " " + p.getPrice());
}
System.out.println("--- record (DTO) projection");
System.out.println(products.findByPriceLessThan(new BigDecimal("100")));
System.out.println("--- JPQL constructor expression");
System.out.println(products.summaries());
System.out.println("--- dynamic projection, chosen by the caller");
System.out.println(products.findByName("Lamp", Summary.class));
System.out.println("--- open projection with @Value");
products.findByCategoryOrderByName("furniture")
.forEach(p -> System.out.println(p.getLabel()));
}
}
}
@Entity
class Product {
@Id
@GeneratedValue
private Long id;
private String name;
private String category;
private BigDecimal price;
private String description;
protected Product() {
}
Product(String name, String category, String price, String description) {
this.name = name;
this.category = category;
this.price = new BigDecimal(price);
this.description = description;
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public BigDecimal getPrice() {
return price;
}
public String getDescription() {
return description;
}
}
interface NameAndPrice {
String getName();
BigDecimal getPrice();
}
record Summary(String name, BigDecimal price) {
}
interface Label {
@Value("#{target.name + ' [' + target.category + ']'}")
String getLabel();
}
interface ProductRepository extends JpaRepository<Product, Long> {
List<NameAndPrice> findByCategory(String category);
List<Summary> findByPriceLessThan(BigDecimal max);
@Query("select new adv.projections.Summary(p.name, p.price) from Product p order by p.name")
List<Summary> summaries();
<T> List<T> findByName(String name, Class<T> type);
List<Label> findByCategoryOrderByName(String category);
}
SQL: select next value for product_seq
SQL: select next value for product_seq
SQL: insert into product (category,description,name,price,id) values (?,?,?,?,?)
SQL: insert into product (category,description,name,price,id) values (?,?,?,?,?)
SQL: insert into product (category,description,name,price,id) values (?,?,?,?,?)
--- interface projection
SQL: select p1_0.name,p1_0.price from product p1_0 where p1_0.category=?
Desk 199.00
Chair 89.50
--- record (DTO) projection
SQL: select p1_0.name,p1_0.price from product p1_0 where p1_0.price<?
[Summary[name=Chair, price=89.50], Summary[name=Lamp, price=24.99]]
--- JPQL constructor expression
SQL: select p1_0.name,p1_0.price from product p1_0 order by p1_0.name
[Summary[name=Chair, price=89.50], Summary[name=Desk, price=199.00], Summary[name=Lamp, price=24.99]]
--- dynamic projection, chosen by the caller
SQL: select p1_0.name,p1_0.price from product p1_0 where p1_0.name=?
[Summary[name=Lamp, price=24.99]]
--- open projection with @Value
SQL: select p1_0.id,p1_0.category,p1_0.description,p1_0.name,p1_0.price from product p1_0 where p1_0.category=? order by p1_0.name
Chair [furniture]
Desk [furniture]
SQL: drop table if exists product cascade
SQL: drop sequence if exists product_seq
- Interface projection:
returnsfindByCategory , an interface with two getters. Spring Data selected onlyNameAndPrice andname , and returned proxies that implement the interface.price - Record projection:
returns thefindByPriceLessThan record, and the SQL again read two columns. Spring Data matches the record's constructor parameters to entity properties by name.Summary - Constructor expression: in a
,@Query builds the record in JPQL. It needs the fully qualified class name, which is why Spring Data's derived form is easier when it fits.select new adv.projections.Summary(p.name, p.price) - Dynamic projection:
lets the caller pick the type. PassingfindByName(String, Class<T>) selected two columns, and passingSummary.class would load the entity.Product.class - Open projection: the
expression on@Value can use any property, so Spring Data cannot know which columns it needs. It loaded all five, includingLabel , and evaluated the expression on the entity. That defeats the point; use a default method on a closed interface, or a record, instead.description
Projections returned this way are not managed, so changes to them are never written back. That makes them a good fit for readOnly
Keyset scrolling with Window
Offset paging asks the database to skip rows, and the database still reads every skipped row: page 10,000 of a large table is slow. Keyset scrolling remembers the last key it returned and asks for "rows after this key", which an index answers directly. Seven events read three at a time show how the position moves:
package adv.scroll;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Map;
import java.util.stream.IntStream;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.domain.ScrollPosition;
import org.springframework.data.domain.Window;
import org.springframework.data.jpa.repository.JpaRepository;
@SpringBootApplication
public class KeysetScroll {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(KeysetScroll.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"logging.pattern.console", "%logger{0}: %msg%n"));
try (var context = app.run(args)) {
LoggingSystem.get(KeysetScroll.class.getClassLoader())
.setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);
EventRepository events = context.getBean(EventRepository.class);
events.saveAll(IntStream.rangeClosed(1, 7)
.mapToObj(i -> new Event("event-" + i)).toList());
ScrollPosition position = ScrollPosition.keyset();
int batch = 1;
while (true) {
Window<Event> window = events.findFirst3ByOrderByIdAsc(position);
System.out.println("Batch " + batch++ + ": " + window.getContent());
if (!window.hasNext()) {
break;
}
position = window.positionAt(window.size() - 1);
}
}
}
}
@Entity
class Event {
@Id
@GeneratedValue
private Long id;
private String name;
protected Event() {
}
Event(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
interface EventRepository extends JpaRepository<Event, Long> {
Window<Event> findFirst3ByOrderByIdAsc(ScrollPosition position);
}
SQL: select next value for event_seq
SQL: select next value for event_seq
SQL: insert into event (name,id) values (?,?)
SQL: insert into event (name,id) values (?,?)
SQL: insert into event (name,id) values (?,?)
SQL: insert into event (name,id) values (?,?)
SQL: insert into event (name,id) values (?,?)
SQL: insert into event (name,id) values (?,?)
SQL: insert into event (name,id) values (?,?)
SQL: select e1_0.id,e1_0.name from event e1_0 order by e1_0.id fetch first ? rows only
Batch 1: [event-1, event-2, event-3]
SQL: select e1_0.id,e1_0.name from event e1_0 where e1_0.id>? order by e1_0.id fetch first ? rows only
Batch 2: [event-4, event-5, event-6]
SQL: select e1_0.id,e1_0.name from event e1_0 where e1_0.id>? order by e1_0.id fetch first ? rows only
Batch 3: [event-7]
SQL: drop table if exists event cascade
SQL: drop sequence if exists event_seq
- The first call used
, an empty position, so the SQL had no condition.ScrollPosition.keyset() captured the id of the last event in the batch. The next query becamewindow.positionAt(window.size() - 1) , with no offset.where id > ?- The third batch held only event-7, and
was false, which ended the loop.hasNext()
The method name sets the batch size with First3OrderByIdAsc
Finding these problems early
- Count statements in tests: with
on, a test can assert that loading a page takes at most a few statements. A change that introduces N+1 then fails a test instead of slowing production.generate_statistics - Log SQL while developing: set
, andlogging.level.org.hibernate.SQL=DEBUG to see the parameter values. Repeated identical statements in the log are the signature of N+1.org.hibernate.orm.jdbc.bind=TRACE - Switch off open-in-view: with
, lazy loading in controllers and JSON serialization fails loudly instead of running hidden queries during the response.spring.jpa.open-in-view=false - Keep to-one associations lazy:
and@ManyToOne are eager by default, and each eager association can add queries to every query of the entity. Add@OneToOne and fetch them explicitly where needed.fetch = FetchType.LAZY - Do not return entities from REST controllers: Jackson walks every getter, triggering lazy loads, and may recurse through bidirectional associations. Return a projection or a record built in the service.
Choosing a fetch strategy
| Situation | Use |
|---|---|
| One query that always needs one collection | JOIN FETCH@Query |
| A derived query that needs associations | @EntityGraph(attributePaths = ...) |
| Code that walks associations in loops, across many use cases | hibernate.default_batch_fetch_size |
| Two or more collections | Fetch one with a join, the others with batch fetching; or Set |
| A page of parents with a collection, on Spring Boot 3 | Page the ids, then fetch the entities by id |
| Read-only lists and API responses | Record or closed interface projections |
| Walking a large table in order | WindowScrollPosition.keyset() |
| Dynamic search filters | Specifications, see |
Measure before and after each change: a statement count from the statistics is a better guide than any rule. For the transaction boundaries that lazy loading depends on, see