In hibernate or OpenJPA, if I do FetchType.EAGER
, I risk loading unnecessary data and hurting performance.
If I do FetchType.LAZY
loading, I risk running into N + 1
problem.
Are there any guidelines what fetch mode to use when?
I agree with the general guidelines suggested by @D.R.:
Lazy loading on one hand imply memory saving, on the other hand imply increasing the number of queries to the db. Eager loading is the opposite.
You have to choose your poison.
Besides, I think it is worth to mention the possibility to override fetching strategies with hibernate fetch profiles (if you plan to use hibernate). When a predefined lazy approach isn't enough flexible, it is a good solution. Using fetch profiles you tell hibernate to fetch object in a "different way" just for that transaction. Very handy when you have to get object lazily, but sometimes you need a different approach.
If you adopt a second level cache optimization, you should check for compatibility since the current fetch profile implementation supports a JOIN strategy.