Turtle Turtle - 3 months ago 14
Java Question

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.

Answer

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 an 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

Comments