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

2
  • 1
    did you actualy search in stackoverflow? the search gives plenty of clues Commented Feb 1, 2010 at 20:46
  • Actually, I did search in StackOverflow and other places. What I found did not seem to give an answer that applied to my problem. If you have some specific post that I might have missed, post it, so I can see if it helps. Commented Feb 2, 2010 at 12:34

3 Answers 3

2

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

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

Comments

2

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.

Comments

1

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.

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.