Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I not use @BatchSize on every lazy loaded relationship?

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.

like image 892
Jan Thomä Avatar asked Jul 02 '13 08:07

Jan Thomä


1 Answers

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.

like image 70
Skyp Avatar answered Oct 16 '22 15:10

Skyp