Alex
Alex

Reputation: 646

How to solve Hibernate's LazyInitializationException

I have CustomerEntity mapped to table customers in database. It has one-to-many relations to orders and addresses. Now I retreive customer with orders with next code:

DetachedCriteria criteria = DetachedCriteria.forClass(CustomerEntity.class);
criteria.add(Restrictions.eq("id", patientId));
criteria.createCriteria("orders", CriteriaSpecification.LEFT_JOIN).add(Restrictions.and(
          Restrictions.isNull("deletedDate"),
          Restrictions.or(Restrictions.isNull("old"), Restrictions.eq("old", BoolType.FALSE))));
CustomerEntity customer = queryDao.searchSingle(criteria);

QueryDAO:

public <T> T searchSingle(DetachedCriteria criteria) {
   return (T) criteria.getExecutableCriteria(getCurrentSession()).uniqueResult();
}

But when I try to invoke customer.getAddresses() next exception is thrown:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: , no session or session was closed

It happens because by default hibernate isn't loaded one-to-many entities. How can I without modifying Customer entity retreive his addresses too?

Upvotes: 0

Views: 257

Answers (2)

Shiraaz.M
Shiraaz.M

Reputation: 3191

There are a few things that can assist you:

  • The use of Hibernate.initialize(customer.getAddresses())
  • You do not show where customer.getAddresses() is used ... so one other method is to use Hibernate Open Session in View (along with other session management strategies mentioned in the previous answer.

Upvotes: 0

Alexey Malev
Alexey Malev

Reputation: 6533

This exception occurs when you try to access the lazy-loading collection or field at the moment when session is not available already. My guess would be - the backend of your application loads data and closes the session, then you pass this data to frontend, for example, where there is no session already.

To resolve this, there are several possible ways to go:

  • Eager loading. Reliable, but possibly slow solution;
  • Changing the way session management is done. Consider strategy session-per-request which is suitable for typical web application. The question Create Hibernate-Session per Request contains information might be usable for you.

For information about another session management strategies, try reading this wiki page.

Upvotes: 1

Related Questions