Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LazyInitializationException in Hibernate : could not initialize proxy - no Session

I call dao from my service as

@Override
@Transactional
public Product getProductById(int id) {
    return productDao.getProductById(id);
}

and in the dao I am getting product as

@Override
public Product getProductById(int id) {
    Product p = sessionFactory.getCurrentSession().load(Product.class, id);
    System.out.print(p);
    return p;
}

This runs fine but if I change my dao class to

@Override
public Product getProductById(int id) {
    return sessionFactory.getCurrentSession().load(Product.class, id);
}

I get org.hibernate.LazyInitializationException: could not initialize proxy - no Session. The exception occurs in view layer where I am just printing the product. I do not understand why returning in same line in dao method results in exception in view layer but works fine if I save it in a reference and then return that.

like image 390
Turtle Avatar asked Aug 20 '16 12:08

Turtle


People also ask

How do I fix Hibernate LazyInitializationException?

The right way to fix a LazyInitializationException is to fetch all required associations within your service layer. The best option for that is to load the entity with all required associations in one query.

Can't initialize proxy no session Hibernate Java?

We have seen that this error mainly comes when you have closed the connection and trying to access the proxy object which is no fully initialized. Since Proxy object needs a connection, you can either reattach object to the session or carefully avoid writing such code, which access uninitialized Proxy object.

What is org Hibernate LazyInitializationException?

Indicates an attempt to access not-yet-fetched data outside of a session context. For example, when an uninitialized proxy or collection is accessed after the session was closed.


1 Answers

This error means that you’re trying to access a lazily-loaded property or collection, but the hibernate session is closed or not available . Lazy loading in Hibernate means that the object will not be populated (via a database query) until the property/collection is accessed in code. Hibernate accomplishes this by creating a dynamic proxy object that will hit the database only when you first use the object. In order for this to work, your object must be attached to an open Hibernate session throughout it’s lifecycle.

If you remove the SOP statement then object is not accessed at all and thus not loaded. And when you try to access it in your other part code of code then it will throw LazyInitializationException.

like image 138
Vivek Goel Avatar answered Sep 20 '22 09:09

Vivek Goel