0

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?

1
  • 1
    I have to wag the finger here: if you had googled "hibernate lazyinitializationexception" you would have gotten a mountain of information on the how, why and how to solve, including plenty of existing stackoverflow threads. Commented Apr 24, 2014 at 9:29

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.