1

I know this error is pretty common but I have searched and nothing seems to work.

I have a recursive relationship in Option entity (childrenOptions, parentOption - as lazy load), and I'm loading a plane list through HQL query like this:

Session session = sessionFactory.openSession();
session.beginTransaction();

List result = session.createQuery("from Option as o").list();

session.getTransaction().commit();
session.close();
return result;

I'm trying to build the user's options tree manually, out of Hibernate session, because it's depend on other Role entities previously loaded.

So, when I try to use getChildrenOptions() property to .add sub-options, I'm getting "could not initialize proxy - no Session" error.

I have already tried session.evict() and .getHibernateLazyInitializer().getImplementation(), but

if (option instanceof HibernateProxy)

is always false.

Is it possible to unable/remove this proxy behaviour and work with collection properties like normal POJO's?

It's seems like a performance issue to eager load all options, I would like to build the tree by myself.

Thanks in advance.

3
  • 1
    it should be enough just not closing the session until you finished with your stuff. Commented Oct 2, 2012 at 21:33
  • thanks @dierre, I think Hibernate is gonna hit the database and lazy-load the childrenOptions collection at getChildrenOptions().add(...) line, if session is still open; basically I already have options filtered in memory (sorry, that's not evident in the simplified hql), all I need to do is build the tree. Commented Oct 2, 2012 at 22:07
  • maybe my answer will help you. Commented Sep 22, 2017 at 7:02

1 Answer 1

0

You must either eager fetch all of these entities while the session is still open, or you must leave the session open for the consumer of your returned list, and only close it when he is finished building the tree. You are loading the list that is full of lazy-load entities, then you are closing the session, then you are shipping it off to some other code which is going to try to traverse that list to build the tree - of course it is going to complain that the session is already closed.

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

2 Comments

thanks @ClayFowler, I totally understand you. To rephrase my question: is it possible to break in anyway the bind or detach my object from its proxy so it can be used to build a subset of options? Thanks for your help!
Either build the tree while the session is still open or eager fetch everything to return to the external tree builder.

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.