Sub topic 8
Reducing queries with batch fetching
This chapter covers batch fetching, a Hibernate setting that cuts the number of lazy-loading queries without changing your entities or queries. It assumes you know the Author and Book model from earlier chapters, can read Hibernate's SQL log, and understand why authorSummaries() issues 1 + N statements.
The idea
Lazy loading is slow in the N+1 case because each uninitialized collection is loaded with its own statement:
select ... from book where author_id = ?Hibernate knows that the persistence context holds many authors whose books collections are still uninitialized. Batch fetching lets it load several of them in one statement. Instead of author_id = ?, it issues author_id in (?, ?, ?, ...).
With a batch size of 50 and 200 authors, the 200 collection queries become 4. The total is 1 + 4 = 5 statements instead of 201.
Batch fetching does not remove lazy loading. It still loads the collection at first access. What changes is how many other collections Hibernate loads in the same round trip.
Enabling it globally
The simplest option is one property:
spring.jpa.properties.hibernate.default_batch_fetch_size=50This applies to every lazy collection and every lazy to-one proxy in the application. You change no entity code and no repository code. The original service method still runs unchanged:
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return authorRepository.findAll().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}With 120 authors and a batch size of 50, the SQL log shows one select ... from author followed by three select ... from book where author_id in (...). The three statements cover 50, 50 and 20 authors.
Verify this with the settings from the detection chapter. Check that getPrepareStatementCount() drops from 121 to 4.
Per-association batching
You can also set the size on a single association with Hibernate's @BatchSize annotation. This is Hibernate-specific and not part of JPA.
import org.hibernate.annotations.BatchSize;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@BatchSize(size = 25)
@OneToMany(mappedBy = "author")
private List<Book> books = new ArrayList<>();
public Long getId() { return id; }
public String getName() { return name; }
public List<Book> getBooks() { return books; }
}Put @BatchSize on a collection field to batch that collection. Put it on an entity class to batch lazy proxies of that entity, for example when many Book rows each point to a lazy Author. A per-association annotation overrides the global default for that association.
Use the global setting as a safety net and @BatchSize only where one association has unusual needs.
How Hibernate builds the IN list
Hibernate does not simply send exactly 50 ids every time. In Hibernate 6, the loader pads or chooses the batch size so the number of distinct SQL shapes stays small. This matters because each distinct statement shape needs its own prepared statement and its own database plan cache entry.
Two consequences:
- The last batch may contain fewer ids than the configured size. In Hibernate 6 the loader may fill unused slots by repeating ids. You will see this in the logs, for example more
?placeholders than uninitialized owners. - The first batch is built around the entity whose collection you touched. Hibernate then picks other uninitialized owners from the persistence context. You cannot control which ones.
Batch loading only considers entities that are already in the current persistence context. This leads to the main limits below.
What batch fetching cannot do
It only helps inside one persistence context
Hibernate looks for other uninitialized collections of the same type in the current session. If each author was loaded in a different transaction, or you touch the collections after the session is closed, nothing is available to batch. A closed session throws LazyInitializationException regardless of batch size.
It does not give you one query
Batching reduces N queries to about N / batch size. It does not reach a single statement. For a list screen with 10,000 authors and a batch size of 50, that is still 200 extra queries. A join fetch or a DTO projection would use one.
It loads whole entities
Every batch loads full Book entities, including columns you may not use. If the code only needs a count, as in authorSummaries(), batching fetches all books to call size(). A projection that returns name and count(b) is cheaper. The DTO chapter covers that.
It may load more than you need
Batching initializes collections for authors that you never touch. If you load 200 authors and read the books of only the first, Hibernate still loads books for the first 50 in one query. The first access triggers a batch for all 50, whether or not you ever read the other 49.
This is usually a good trade, since one wider query is cheaper than 50 narrow ones. It becomes wasteful if each collection is large and rarely read.
Eager associations and batch size
Batch size also affects FetchType.EAGER associations that Hibernate loads with follow-up selects. Hibernate loads such associations with a secondary select, for example when you load an entity through a JPQL query. The setting reduces those extra selects in the same way.
Choosing a batch size
There is no universal value. Reasoning about the trade-offs helps:
| Batch size | Effect | Typical use |
|---|---|---|
| 5 to 10 | Small IN lists, still many queries for large pages | Collections that are very large per owner |
| 20 to 50 | Good balance between round trips and IN list length | Most applications |
| 100 or more | Few round trips, very long IN lists | Narrow rows, simple keys |
Points to check when you pick a number:
- Page size. If your screens show 20 rows at a time, a batch size of 20 or more turns the N queries into one.
- Database limits. Some databases limit the number of bind parameters in a statement. Oracle limits an IN list to 1,000 expressions. SQL Server limits a statement to 2,100 parameters. Stay well under those.
- Rows per batch. If each author has 500 books, a batch of 50 loads 25,000 rows at once. Memory use grows with batch size times collection size.
- Plan caching. A few distinct batch sizes keep the database's plan cache small.
Measure with the statistics from the detection chapter rather than guessing. Compare statement count and total time under realistic data volumes.
Comparing batch fetching with the other fixes
| Approach | Statements for N authors | Changes needed | Notes |
|---|---|---|---|
| Lazy, no fix | 1 + N | None | The problem case |
| `default_batch_fetch_size=50` | 1 + N / 50 | One property | Works with pagination of the parent |
| `join fetch` | 1 | Query | Breaks paging of the parent, see the collection pitfalls chapter |
| `@EntityGraph` | 1 | Repository method | Same limits as join fetch |
| DTO projection | 1 | Query and DTO | No entities, read-only |
The row "works with pagination of the parent" is the main reason to reach for batch fetching. Paging a plain Author query with Pageable uses a SQL limit directly, because no collection is joined. The collections are then loaded lazily in batches for the page's authors only.
public interface AuthorPagingRepository extends JpaRepository<Author, Long> {
}@Transactional(readOnly = true)
public List<String> pageSummaries(int page) {
return authorPagingRepository.findAll(PageRequest.of(page, 20, Sort.by("id")))
.stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}Here the page has 20 authors. With a batch size of 50, the log shows one author query with a limit, plus one book query with an IN list for all 20 authors. That is 2 statements, and the paging happens in the database.
This is why batch fetching is the usual answer when a list endpoint needs both a page of parents and their children.
Common mistakes
- Expecting the property to remove all extra queries. The log still shows several selects. That is expected. The goal is a count that no longer grows with N.
- Setting a huge size such as 1000. This can exceed database parameter limits and produce very large plans.
- Using the property to cover a design problem. If a screen needs only a count, change the query instead of loading all the child rows.
- Setting it only in a test profile. Put it in the shared
application.properties, or the production behavior will differ from what you measured. - Forgetting the transaction boundary. A batch can only form while the session is open. With
spring.jpa.open-in-view=false, access the collections inside the@Transactionalservice method.
Summary of the working model
- Hibernate loads the parent list with one query.
- At the first access of an uninitialized collection, it collects the owner ids of up to
batch sizeuninitialized collections in the session. - It runs one
inquery for those ids and initializes all of those collections. - Later accesses to those collections cost no query. The next batch is built when the first collection outside the loaded set is touched.
Exercise
A list endpoint loads a page of 30 authors with findAll(PageRequest.of(0, 30)), then calls getBooks().size() on each one inside a transaction. default_batch_fetch_size is 10. How many SQL statements does Hibernate issue, and why can't a join fetch on books replace this setup while keeping database-side paging?
Show answer
It issues 1 + 3 = 4 statements: one paged author query, then three book queries, each with an IN list of 10 author ids. A collection join fetch multiplies author rows by their books, so Hibernate cannot apply the page limit in SQL. It would apply it in memory after loading every row, with a warning in the log. Batch fetching keeps the limit in the author query and loads the books separately.
Exercise
You set default_batch_fetch_size=50, but the log still shows 201 queries for 200 authors, each using author_id = ?. Name two likely causes.
Show answer
Likely causes are that the property was set in the wrong place or with the wrong name, so Hibernate never reads it. It must be spring.jpa.properties.hibernate.default_batch_fetch_size. Another cause is that each author's collection is touched in a separate session or transaction, so there are no other uninitialized collections in the same persistence context to batch with.