jasilva
jasilva

Reputation: 750

Only in jsp javax.el.ELException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session

Hello i have a web app spring+hibernate

I jsp i tried to read a state of a product

<p>${product.state }</p>

In my POJO class

public class Product
{
   ...
   public String getState(){
       if(this.type == 6)
         return "A";
       if(propertyB.getRole()== 15)
         return "B"
   }
}

when a product looking to access a property that is another entity like propertyB Throws

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

Because i change my query with LEFT JOIN FETCH

FROM Product p LEFT JOIN FETCH p.propertyB b

When i get a list of my prodcuts in a Test of Junit works

When i get a list of my products in my jsp file Throws

javax.el.ELException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session

When i get a list of my products in the Controller like

for(Product p: listOfProducts){
    log.put(p.getState());
}

Works fine!!

But only in jsp not work why?

Upvotes: 0

Views: 1134

Answers (3)

Matt Jennings
Matt Jennings

Reputation: 1148

Use OpenEntityManagerInViewFilter. It's a filter that will attach a database session to the thread that is rendering the jsp.

You set it up in your web.xml just as you would any other J2EE filter.

Upvotes: 2

Mukus
Mukus

Reputation: 5033

Set it to Eager fetch if you want to automatically resolve the child property. If not, you will need to query the child passing the parent's id. The latter is probably the preferred way of doing (at least for me), because you may not always need to eagerly fetch the children. This will however require a new hibernate session.

I think with your unit test, you initialize session before every test.

Upvotes: 0

Nuno Neto
Nuno Neto

Reputation: 303

Try using Hibernate.initialize(yourObject) before passing it on to the model.

Upvotes: 0

Related Questions