@ManyToOne associated with @BatchSize can only make sense if the corresponding field is marked as lazy ( lazy=true ).
In fact, if the field is not lazy , it is already loaded by definition, since the loadable object is loaded, so the problem with database calls does not apply.
Imagine a Person class that has a collection of the ShoesPair element ( ShoesPair .class), and this field contains the owner field marked as lazy (since it is optional and does not bring important information when retrieving a specific pair of shoes).
One wants to repeat a pair of 25 pairs of shoes (25 ShoesPair objects) to get their owner.
If the owner field (corresponding to one person) is annotated only with @ManyToOne , the database will be 25 .
However, if annotated using @BatchSize(size=5) , there will only be 5 calls, and therefore an increase in performance.
From the Hibernate documentation , it is clarified that batch size does not apply only to collections:
You can also enable batch sampling of collections.
Hibenate is especially relevant for @OneToMany cases, because they apply with fields that are marked as lazy in 90% of cases.
source share