I am attempting to create a web application using Spring MVC, with Hibernate as its ORM layer. However, due to my inexperience with both frameworks I\'m struggling.
Actually,there are three ways to avoid the Lazy Initialization Exception:
Set the lazy property to false in the mapping file.I don’t recommend this approach because it will increment the database load and therefore, it will produce a decrease in performance.
Keep the session open. Don't close the session before you have processed the data. If the session is open during the request you could get the associated graph but you need to be sure that the action takes within the same transaction.
Eagerly fetch the associations. In the HQL query use the keyword "fetch" to retrieve the association. From my point of view this is the best solution to avoid the lazy initialization problem. In HQL, you just need to add the fetch keyword in the from clause to eagerly fetch an association.
Here is an example:
from Doctor doc
left join fetch doc.patients
where doc.name like ‘Doctor A%’
I have written a post about this issue, with some code examples and links to the github project:
http://ignaciosuay.com/how-to-avoid-hibernate-lazy-initialization-exception/