The @BatchSize annotation of hibernate allows for batched fetching of lazy-loaded entities. E.g. if i got something like:
public class Product {
@OneToMany(fetchType=LAZY)
@BatchSize(size=10)
private ProductCategory category;
}
Now if I get the category of a product, Hibernate will fetch the categories of up to ten more products which are in the current session and have not yet had their category field initialized. This saves a ton of SQL calls to the database. So far so good. Now I wonder why would I not use the @BatchSize annotation on EVERY lazy loaded relationship? After all why would I want extra calls to the database? There clearly must be a reason for this, otherwise the Hibernate guys could have made it the default, but I currently can't see it.
I am not going to answer to your question directly but I am going to answer a more generic question which could be "I have found something that works quicker for me, Why not apply it everywhere ?"
The short answer is : You should not do preemptive optimization.
hibernate is a wonderful ORM that allows all kind of optimization. You should measure all the processes that causes an issue (the classic N+1 even if it is fast, any slow processes, etc.) and optimize to solve it.
You might gain a lot better performance by eager loading some properties because you always use them, you might need a BatchSize
of 100 for some other because you know it's about the number of relations you have for that property.
Ultimately, you should not care about optimization unless you need to care about it. And you need to care when you have done measurements and found issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With