when to use Lazy loading / Eager loading in hibernate?
I am trying to understand where to use lazy loading and where to use eager loading, highly appreciate your insight.
Here are a few thoughts:
1) If you are going to always use something (for sure), you can eager load it.
2) Related to 1, if you are almost never going to use something, lazy load it.
3) Lazy loading tends to be more useful when large collections are involved.
4) Eagerly loading things will reduce session-related errors, at the potential cost of a performance hit.
5) For complicated data models and/or large databases, you are going to see how your app does under load an adjust your strategies.
6) It's difficult to get it right the first time. Do what feels right, and don't be afraid to change if necessary.
7) For large datasets, you are going to probably end up writing custom hql/queries anyway, where the default mappings can be overwritten, so lazy vs eager won't matter so much.
If you believe #6, then don't get stuck trying to plan too far ahead, and change it if you have to.
WRT your specific example, I would probably write a bunch of queries to access the data (driven by appropriate business needs, of course)
1) A query that loads the customer, and leaves the orders in the db (so lazy loading) that I would call when I need to get customer info
2) A query that loads the customer and all order info, for cases where I need it. So this case I'll ignore the default mapping.
With those two queries in place, in my service layers I have the tools I need to do what is correct based on the context of the situation.
This link perfectly answers your question.
LAZY loading is used in cases where the related entity size is huge and it's not required to be fetched every time on the other hand
EAGER should be used with proper analysis as it loads the relationship every time the main entity is loaded.
So if a relationship is absolutely necessary for business logic computation you should think of making use of EAGER loading; LAZY loading will serve most of the cases and provides less performance trouble.