I’m working on a project using JBoss 6.1.0.Final, JSF 2.0.3, EJB3 and JPA 2 + Hibernate 3.3.
A JSF page is showing a form to input data of an entity A, while it also has a list of B, C and D entities, associated to that entity A. One of those lists is shown while loading the form and that one is the one throwing LazyInitializationException because there is no session or the session was closed.
After some SO & Google browsing I tried some answers, and a pattern to keep the EntityManager in the view but none of those suffice. Spring has an org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor that seems to handle this situation AFAIK but I can be wrong.
The Exception is thrown when executing any method accessing the list:
IA entityA = business.getListOfAs();// In AListBean
And then, on the form I do:
entityA.getListofB(); //LazyInitializationException
I don’t access the list as soon as I fetch the A record, there is some navigation in the middle which causes the session to be closed before I fetch the list of B items.
Reattaching the detached instance of A solves the problem, but I don’t know how can I do it without merging the object (persisting any changes made to it) and setting the fetch type to eager is not an option.
Is thre any way to access the lists of B, C and D entities in A in a lazy approach?
If A is detached from its Session you can seperately load the B collection and set it via its Setter if you don’t want to reattach it.
Seperately load the collection and set it via the setter before you access it using gui events.
Load the collection in the EJB’s using HQL or criteria API like:
In the JSF managed beans use properties and a update method connected to gui events like: