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?
2 Answers
In general you should use eager fetching in all cases where you immediately afterwards need the data. If you run into the N+1 problem, just re-execute the query with eager fetching.
There are of course much more opinions for more specific situations, however, I guess, SO is not the best place to discuss things.

- 20,268
- 21
- 102
- 205
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.

- 2,505
- 7
- 28
- 50