问题
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: pojo.Person.address, no session or session was closed.
I am getting this exception and I'm using Spring 3.0 and Hibernate 3.6.
回答1:
It looks like you have an Entity called Person which has a lazily loaded mapped collection of Addresses? You have loaded the Person and the session it was loaded in has now been closed.
After the session was closed you then attempted to access that collection of address and Hibernate attempted to load them. However, that is not possible if the original session is no longer available.
In order to access the address property you have a few options:
Use the OpenSessionInView pattern to ensure that the Hibernate session is held open for the duration of the request/response cycle (Since you've tagged Spring MVC I'll assume this is a web based operation). This essentially scopes your Hibernate session to the HTTP request.
Ensure that all required properties are loaded before the session is closed (transaction committed). You can do this using
Hibernate.initialize(person.address)
or by writing HQL that uses a left join fetch. This could be something like:
createQuery("from Person as person left join fetch person.address")
This will override any lazy loading configuration for this query only and ensure that any collections are initialized.
回答2:
Most probably, you don't have transaction management set up. That is, Spring uses default transaction scope, which is transaction per HibernateTemplate
call, and closes session right after return from HibernateTemplate
.
You can do one of three things:
- set up transactions,
- switch to explicit session handling,
- use Criteria API or
fetch join
in order to prefetch the details you need.
回答3:
I was seeing this issue because I had failed to annotate a method in a service with @Transactional
. It seems that Hibernate closes the session when a call to another method is made (even within the same class) unless the caller is annotated appropriately.
来源:https://stackoverflow.com/questions/8292820/org-hibernate-lazyinitialization-exception