ERROR - Hibernate - org.hibernate.LazyInitializationException: failed to lazily initialize

Error

org.hibernate.LazyInitializationException: failed to lazily initialize


while using Hibernate and loading the Enitity.

Error Type

Runtime

Cause

Hibernate has the feature to lazily initialize dependencies , relationship and associations from the Database. Any related references marked as @OneToMany or @ManyToMany are loaded lazily i.e when they are accessed and not when the parent is loaded. Seems like the session is closed before any reference to the dependent object is made.

Resolution 1

Set lazy=false in the hibernate config file.

Resolution 2

Set 
@Basic(fetch=FetchType.EAGER) at the mapping or
@[ManyToOne,OneToMany](fetch = FetchType.EAGER)

Resolution 3
Make sure that we are accessing the dependent objects before closing the session.

Resolution4

Add a trick to keep the session open or manage the session in a way to close the session upon completion of request. Filter can be added to better handle the session.