How to Use Hibernate Batch Fetch Size to Tame N plus 1
Use Hibernate batch fetch size to turn N plus 1 queries into a few IN queries: global setting, per association annotation, trade-offs and how to verify.

The N+1 problem has a well-known cure in the join fetch, and a quieter one that needs no change to any query: batch fetching. Instead of loading each lazy association with its own select, Hibernate collects several pending loads and issues one statement with an IN list. A list of fifty orders, each touching its customer, stops costing fifty-one queries and costs a handful. It is the right first fix when the code is spread over many places or the query shape is dictated by a framework. This post shows the setting, the per-association form, how to choose the size, how it compares to a join fetch and how to prove that it works. It uses Hibernate 7 and Spring Boot 4 on JDK 25.
The problem
@Entity
class Order {
@Id Long id;
@ManyToOne(fetch = FetchType.LAZY)
Customer customer;
@OneToMany(mappedBy = "order")
List<OrderLine> lines = new ArrayList<>();
}List<Order> orders = repository.findAll(); // 1 query
for (Order o : orders) {
System.out.println(o.getCustomer().getName()); // 1 query per distinct customer
}Each o.getCustomer() is a proxy, and reading the name initialises it with select ... from customer where id = ?. Fifty orders from fifty customers means fifty-one statements. Each is cheap, and the sum is a page that takes a second instead of ten milliseconds, with network latency to the database multiplying the effect. The general diagnosis and the other fixes are in the N+1 problem.
Turn on batch fetching
spring.jpa.properties.hibernate.default_batch_fetch_size=16With this setting, when Hibernate must initialise one customer proxy, it looks at the other uninitialised customer proxies in the same persistence context and loads up to sixteen of them in one statement:
select c.* from customer c where c.id in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)Fifty customers take four statements instead of fifty. The same applies to lazy collections: the first access to order.getLines() loads the lines for up to sixteen orders in one IN query on the foreign key. Nothing changes in the repository or the loop; the query count drops by a factor of the batch size. The setting is global, so it affects every lazy association in the application. That is convenient and also a reason to verify with the SQL log after enabling it.
Per association
If you want to limit the change, annotate one association or entity:
@ManyToOne(fetch = FetchType.LAZY)
@BatchSize(size = 25)
Customer customer;
@OneToMany(mappedBy = "order")
@BatchSize(size = 25)
List<OrderLine> lines;On a collection or a to-one association, @BatchSize applies to loading that association. On an entity class, @BatchSize(size = 25) applies to loading proxies of that entity wherever they come from. The annotation overrides the global default for the element it sits on. Use the per-association form to adopt batching gradually, and use the global setting for a codebase where the honest default should be "never one query per row".
Choosing a size
There is no universally correct number, but there are constraints. The size should be close to your typical list length: a screen showing twenty-five rows benefits from a batch size of 25 or more, and 16 leaves a second query for the remainder. Hibernate does not build an IN list of arbitrary length; it pads to a small set of sizes to reuse prepared statements. With a configured size of 16, it uses fixed sizes derived from it (for instance 16, 8, 4, 2, 1), so a load of fifty ids becomes three batches of 16 and then smaller ones. The effect is that very large values give diminishing returns and fill the database's statement cache with differently shaped queries.
Databases limit the number of bind parameters: PostgreSQL's driver accepts up to 32,767 parameters, SQL Server 2,100, Oracle caps an IN list at 1,000 expressions. Stay well below those. Sixteen to one hundred is the usual range. Measure with a realistic page: pick the smallest size that brings the count to two or three statements.
Batch fetch versus join fetch
A join fetch loads the association in the same statement as the parent:
@Query("select o from Order o join fetch o.customer")
List<Order> findAllWithCustomer();That is one statement, always, and it is the better tool when you know exactly what the use case needs. Batch fetching still issues extra statements, roughly N divided by the batch size, and it only happens when the association is touched. In exchange, it needs no query changes, works with findAll, with derived queries, and with lazy loads that happen deep in a template, and it does not duplicate parent rows in the result set.
Join fetching a collection multiplies rows (an order with ten lines returns ten rows), breaks paging (Hibernate then paginates in memory and warns about HHH000104), and cannot fetch two List collections at once without a MultipleBagFetchException, covered in multiple bag fetch. Batch fetching has none of those restrictions, which is why it is the standard answer for collections and for paged lists. A sensible combination is a join fetch for the to-one associations that every use case needs, and batch fetching for collections and the rest.
When the screen needs only a few columns, a projection avoids loading entities at all; see DTO projections. Loading entities you only read is wasteful whatever the fetch strategy.
Verify it
Do not trust the annotation. Count the statements. Turn on SQL logging in development, or use Hibernate's statistics:
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.stat=DEBUGand read the line that reports the number of JDBC statements for the session. For a regression test, assert the count in an integration test with a library such as datasource-assert, or with the statistics API, so that a later change that removes the batching fails the build. The approach is shown in counting statements and in detecting N+1 queries in tests.
Pitfalls
Batch fetching works within one persistence context. If the proxies are initialised in different sessions, each loads alone. It also works only for the proxies that exist when the first one is initialised: with open-in-view off and loads spread over separate transactions, the batch is smaller than expected. The first access still pays a round trip, so a page with three levels of lazy associations pays three batched queries in sequence, each waiting on the previous one. If the latency per query is high, as it is across data centres, a join fetch or a single projection query is faster.
Batching interacts with @Where, soft deletes and filters, because the batch query applies the same restrictions; that is correct, and it means a deleted parent is absent from the batch. Finally, the setting does not help with LazyInitializationException: if the session is closed when you touch the proxy, no query can be issued. The fix there is in the lazy loading error.
When this does not apply
For associations that are always needed together, make the use case explicit with a join fetch or an entity graph. For read-heavy reports, use native SQL or projections. The annotation is documented in the BatchSize Javadoc and the mechanism in the user guide.


