Reputation: 2720
My Java Web application uses Hibernate to perform ORM. In some of my objects, I use lazy loading to avoid getting data until I absolutely need it. The problem is that I load the initial object in a session, and then that session is destroyed. When I later attempt to resolve the lazy-loaded collections in my object I get the following error:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: common.model.impl.User.groups, no session or session was closed
I tried associating a new session with the collection and then resolving, but this gives the same results.
Does anyone know how I can resolve the lazy collections once the original session is gone?
Thanks...
--Steve
Upvotes: 2
Views: 1584
Reputation: 1210
You have a few options, but the main issue is that you need to either extend your session, or reattach your objects to the session.
Pascal provided the answer as to how to re-attached objects to a new session.
Another option is to change the way you are handling Sessions. In our application, we also use Spring, and let Spring manage Hibernate's sessions for us. This provides a good portion of the solution, but you'll still need to re-attach objects from time-to-time, that is just part of the way you use Hibernate in web environments.
Upvotes: 1
Reputation: 597026
Three options:
call Hibernate.initialize(..)
on your collection whenever it is about to get disconnected from the current session
declare the collection as FetchType.EAGER
merge(..)
your user object back to the new session
Upvotes: 2
Reputation: 570295
Before accessing uninitialized collections or other proxies, you need to attach a previously loaded object to a new Session
with merge()
or lock()
. I don't know how you did this in your case but the fact is that your User
was still detached when you tried to retrieve his groups
.
Upvotes: 2