I found in some old code strange thing (at least for me).
The field which is annotated @ManyToOne is also annotated with @BatchSize.
I always thought that @BatchSize annotation only affects when annotated at class level or on a collection (@OneToMany) and affects pre-fetching when iterating.
But maybe I am wrong and annotating @ManyToOne with @BatchSize affects something. I can’t find the answer in the documentation.
Does annotating @ManyToOne with @BatchSize have sense?
@ManyToOneassociated with@BatchSizecould make sense only if the corresponding field is marked aslazy(lazy=true).Indeed, if the field is not
lazy, it’s by definition already loaded since the enclosing entity is loaded, so the problem of database calls doesn’t apply.Imagine a
Personclass who has a collection ofShoesPairelement (ShoesPair.class) and within this one is present anownerfield marked as lazy (since optional and not really bringing an important information when retrieving a specific pair of shoes).One wants to iterate through 25 pair of shoes (25
ShoesPairobjects) in order to retrieve their owner.If the
ownerfield (corresponding to one person) is only annotated with@ManyToOne, there would be 25 select to database.However, if annoted with
@BatchSize(size=5), there would be merely 5 calls and so increasing performance.From the Hibernate documentation, it is precised that batch size does not only apply with collections:
Hibenate mentions especially
@OneToManycases, because these one are applied with fields that are in 90% of cases marked aslazy.