LazyInitializationException in Hibernate : could not initialize proxy - no Session

Here's a good reference to get you familiar with how .get() and .load() method works.

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

session.load() by default returns a proxy object without hitting a database. It basically returns NoObjectFoundError if there aren't any records on the table or else it will return a reference without populating the actual object or even hitting the database. Your above method returns a proxy and since it has to initialize the your object as well, the session remains open and object is populated.

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

But in your second method, basically a proxy is returned without any initialization. session is closed thereafter without any prior use. Thus you get the error.

Hope that helps


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.