I’m using Spring 3.1 and Hibernate 4 in a console application (i’m trying some functionalities of these frameworks and their integration).
How can I solve Hibernate LazyInitializationExceptioin in a non-web-application?
I’ve red about using OpenSessionInViewFilter, but none about applications that don’t use servlets…
Which is the right way to solve the issue?
Before returning the instances loaded by hibernate to the view layer of your console application , always make sure that the entities that you need to display or access in the view layer are initialized .
You can force initialize an entities using the following methods:
Hibernate.initialize():
For example , you have have to display all the
orderDetailfor anOrderin the view layer but your console application only load anorderinstance. AssumeorderDetailis lazy loaded , before returning theorderto the view layer , callHibernate.initialize(order.getOrderDetail())Use the fetch join to fetch the
orderDetailalong with theorderwhich causes the returnedorderobject have theirorderDetailfully initialized :SELECT order FROM Order order join fetch order.orderDetail
Update :
fetch = FetchType.EAGERon the@OneToManyis the 3rd option. It will cause that if aorderis loaded , itsorderDetailwill also be automatically loaded and initialized too .But this affects globally. We normally don’t change the default lazy fetch plan of@OneToManyto eager fetching in mapping metadata unless it is absolutely sure to do it . Instead , we use thefetch join(option 2) to override the default lazy fetch plan to be eagerly fetched for a particualr use case.