Hibernate / EclipseLink Interview questions
What is the difference between EAGER and LAZY fetch strategies, and how does EclipseLink implement lazy loading without a live session?
FetchType.EAGER loads a relationship immediately, as part of the owning entity's initial query. FetchType.LAZY defers loading until the relationship is actually accessed, which is more efficient when the related data often isn't needed, but introduces the classic risk of trying to access it after the persistence context that could load it is already gone.
| EAGER | LAZY |
| Loaded immediately with the owning entity. | Loaded on first access, if ever. |
| Safe to access after detachment. | Risk of failure or empty data if accessed after detachment, unless already resolved. |
| Can cause unnecessary joins/queries for unused data. | Avoids loading data that's never actually used. |
EclipseLink's answer to the "session already closed" problem, common with Hibernate's LazyInitializationException, is weaving-based indirection: a lazy attribute is backed by a special proxy-like object holding enough information (the owning entity's identity and the mapping) to trigger its own fetch on demand, using whatever active session or connection is available at access time, rather than strictly requiring the exact original persistence context to still be open. This makes EclipseLink somewhat more forgiving of lazy access after detachment than some alternative providers, though relying on it as a substitute for correct fetch-scope design is still fragile and best avoided.
More Related questions...