Video in progress

How do `@BatchSize` or `hibernate.default_batch_fetch_size` ease the N+1 problem?

Lazy associations are loaded in groups instead of one at a time: Hibernate sends a single where id in (?, ?, ...) query for several parents in the context. Instead of 100 SELECTs you get 2-3, and you don't have to rewrite the queries.

📖 Answer

A simple case: 100 Departments are loaded, then getEmployees() is called on each.

Without the setting:

select * from employee where department_id = ?   -- 100 times

With the global setting:

spring.jpa.properties.hibernate.default_batch_fetch_size=50
select * from employee where department_id in (?, ?, ..., ?)  -- 2 times

Or for just one place:

@OneToMany(mappedBy = "department")
@BatchSize(size = 50)
private List<Employee> employees;

If you put @BatchSize on an entity class, the proxies of that entity (those that arrive through a @ManyToOne) are loaded in groups too.

Why I like it: unlike join fetch, the result doesn't multiply (no Cartesian product), pagination isn't broken, and it's safe to use several collections together. The downside is that there are still several queries, and they go out only when the lazy association is first accessed.

That's why I often turn on a global default_batch_fetch_size in the 20-100 range. It's a safe "floor". On the hottest endpoints I still write an explicit join fetch or a DTO.