Question

I am using jquery for UI , Struts2 as Action , JPA for Data Access Layer. The issue I am facing is that I am getting LazyInitializationException when I am trying to retrieve values from the database . I am getting the below stacktrace :

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.singpost.ctf.core.persistence.CtfTxn.ctfTxnAttribs, no session or session was closed

By default the Fetch="LAZY" , the code is working fine when I changed the Fetch type to EAGER, I don't know what I have to do further. I am stuck in the middle .

Was it helpful?

Solution

if you try to access a lazy fetched attribute from an entity JPA tries to access the database again to fetch the data. your problem is that at this time you're outside of the transaction. there are many ways to extend your transaction, e.g. using openSessionInViewFilter

( Hibernate/Spring: failed to lazily initialize - no session or session was closed )

what i personally prefer is to create transfer objects, one for every page you want to show, only including necessary data. you only need to map your entities into those transfer objects, e.g. using the dozer mapper, which is really powerful and convenient. that way it's much easier to manage transactions, and secondly you don't use database entities in your frontend, because you frontend doesn't need to know anything about your persistence layer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top