views:

183

answers:

2

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

+1  A: 

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.

Pascal Thivent
+1  A: 

Three options:

  1. call Hibernate.initialize(..) on your collection whenever it is about to get disconnected from the current session

  2. declare the collection as FetchType.EAGER

  3. merge(..) your user object back to the new session

Bozho