Lazy loading and its exception
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
explain lazy versus eager and LazyInitializationException.
Planned topics
- Lazy: the relation is loaded on first access, using a proxy placeholder.
- Eager: loaded immediately with the parent, always, even when unused.
LazyInitializationException: you touched a lazy relation after the persistence context closed.- Do not "fix" it by making everything
EAGER; that creates huge hidden queries. - Load what you need inside the service transaction, or use a projection/DTO.
Draft outline details
Demonstration
Order o = orderService.find(1L); // transaction ended here
o.getLines().size(); // LazyInitializationExceptionCheck your understanding
Why does LazyInitializationException happen?
Show answer
The relation was read after the session closed.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.