API / Apache Grails Interview questions
How do you troubleshoot a LazyInitializationException in a Grails application?
This exception fires when code tries to access a lazily-loaded GORM association (a collection or a related object that wasn't eagerly fetched) after the database session/transaction that could have loaded it has already closed — a classic symptom of accessing persistence-backed data outside the boundary where persistence is actually active.
- Identify exactly where the access happens — the stack trace names the specific association; common culprits are a GSP view iterating over a lazy collection after the controller action (and its transaction) has already returned, or a background thread touching an entity loaded in a different request's session.
- Fetch eagerly where the data is genuinely needed — if a view always needs an association, mark it eager in the domain class mapping or fetch it explicitly in the controller/service before the session closes, rather than relying on lazy loading to somehow still work later.
- Keep the session open through rendering for cases genuinely tied to view rendering, using Grails' open-session-in-view support (enabled by default in many setups) so the persistence context stays available through the whole request, including view rendering.
- Avoid passing detached entities across transaction boundaries — re-fetch or re-attach an entity within the new transaction/session rather than assuming an object loaded earlier is still safely lazy-loadable.
The recurring theme is that lazy loading only works while the originating persistence session is still open — the fix is always either bringing the needed data inside that window (eager fetching) or keeping the window open long enough to cover where the data is actually accessed.