Sub topic 8
Reducing queries with batch fetching
This chapter assumes you know basic JPA mapping, Spring Data repositories, and the Author and Book model from earlier chapters. You should also have seen how lazy loading produces N+1 queries.
What batch fetching does
JOIN FETCH and @EntityGraph change a specific query. Batch fetching works differently. It changes how Hibernate initializes lazy collections and proxies. Instead of loading one collection per statement, Hibernate loads several at once with an IN clause.
Your code stays the same. Only configuration changes, so it is a good fit when many queries touch lazy associations and you don't want to edit each one.
Enabling it globally
Add one property:
spring.jpa.properties.hibernate.default_batch_fetch_size=50With this setting, Hibernate loads lazy collections and proxies for up to 50 parent entities per statement. N extra queries become roughly N/50.
Seeing the effect
Take the service method from the N+1 chapter:
@Service
public class AuthorService {
private final AuthorRepository authorRepository;
public AuthorService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
@Transactional(readOnly = true)
public List<String> authorSummaries() {
return authorRepository.findAll().stream()
.map(a -> a.getName() + ": " + a.getBooks().size())
.toList();
}
}Suppose the table holds 120 authors. Without batching, this runs 1 + 120 = 121 statements. With a batch size of 50, it runs 1 query for the authors. The first call to getBooks() then loads the books of 50 authors at once. Two more statements cover the remaining 70 authors. That makes 4 statements in total.
Hibernate may also use smaller IN lists when the final batch is not full, so the exact count can vary slightly between versions. Confirm it with the SQL log and statistics described earlier.
Setting it per association
You can also limit batching to one association with @BatchSize:
import jakarta.persistence.*;
import org.hibernate.annotations.BatchSize;
import java.util.ArrayList;
import java.util.List;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author")
@BatchSize(size = 50)
private List<Book> books = new ArrayList<>();
}The annotation overrides the global default for that association. Use it when only some associations benefit from batching.
Trade-offs
- Fewer queries, not one query. You still run several statements. The count grows with the data, only more slowly.
- No Cartesian product. Each statement selects one kind of row, so you avoid the duplicated parent rows of a join. This also avoids the in-memory pagination problem that collection fetch joins cause.
- It loads everything in the batch. If you touch the books of one author, Hibernate may still load the books of up to 49 other authors in that statement. That is wasted work when you need few of them.
- It works only while the session is open. Lazy loading still needs an active persistence context. Batching does not fix a
LazyInitializationException. - Batch size is a guess. Values between 10 and 100 are common. Larger lists make bigger
INclauses, which some databases handle poorly.
Exercise
A service loads 200 authors with findAll() and reads getBooks() on each. The global batch fetch size is 50. About how many statements run, and why is this not a single statement?
Show answer
About 5: one for the authors and four for the books, since 200 authors divided into batches of 50 gives 4 IN-clause queries. Batch fetching reduces N queries to N/batch size. It does not merge them into one. A JOIN FETCH or a DTO projection would be needed for a single statement.