Hibernate – Lazy Fetch strategy vs Eager Fetch strategy in hibernate


I went through the Hibernate Tutorial at http://docs.jboss.org/hibernate/core/3.3/reference/en/html/performance.html and got the question which fetch strategy among select or Join is better and we should go for. I know most of the guys will say it depends upon your requirement.But in most of the web applications we have common requirements i.e performance should be good. Here is my understanding :-

Lazy/Select Fetch strategy:- Select Fetch strategy is the lazy fetching of associations. The purpose of Lazy strategy is memory optimization . When I say memory optimization it means it means it saves us from heap error. This is what I think. So we can say yes if we are loading too objects in aseesion we should go for
Lazy Fetch strategy but in terms of time performance it does not provide any Benefit. Agreed?

Eager/Join Fetch strategy:- Join Fetch strategy the eager fetching of associations.The purpose of Join Fetch strategy is optimization in terms of time.I mean even associations are fetched right at the time of fetching parent object. So in this case we don’t make database call again and again . So this will be much faster.Agreed that this will bad if we are fetching too many objects in a session because we can get java heap error.

So now can we say in the hibernate session where we are not loading too many objects we should go for Eager fetch as it will be much better in terms of time response(Any ways memory will be reclaimed by garbage collector once we close the session)?

Best Answer

Go for Join if you need the data to be loaded and Select if you usually don't need it.

About the Java Heap Error do not worry too much. You must be loading tons of objects. You can set up the batch size. The load of the object is not the only strategy.

If you do not need to load all objects you can add specific HQL or Criterias.

If you need more than you don't the object go for Join otherwise Select.