Reputation: 646
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
Reputation: 3191
There are a few things that can assist you:
Hibernate.initialize(customer.getAddresses())
Upvotes: 0
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:
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