imma

Just my thoughts and glimpses of me

Hibernate Exception: Illegal attempt to associate a collection with two open sessions

That is the error that I have been trying to solve for the last two days and the solution turned out to be something very straight forward (and dare I say simple); the proper exception thrown was: org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions.

Cause: It showed up when I attempt to update an element in a collection; adding to the collection was not a problem, hibernate mapping files are ok and everything else seemed to be in order but the error keeps turning up.

Solution: it turned out that I was preserving a value across requests whose presence cause a select statement to be executed before the update hence the exception.

Hmm … I can now get back to making some lightening fast progress.

March 9, 2007 - Posted by imma | Development | | 6 Comments

6 Comments »

  1. I get the same exception, and I do not understand what u mean by “it turned out that I was preserving a value across requests whose presence cause a select statement to be executed before the update hence the exception.”

    can u give more explanation ..it is my second day in this one

    Comment by Emad | May 19, 2008

  2. A little context about the exception mentioned: I was using Hibernate, Spring and JSF. I was trying to update the collection using a JSF managed bean that has a request scope. Note that the hibernate data access object is managed by Spring hence is not (in my setup) part of JSF life cycle.

    So with the above scenario, the first request attaches the collection to a hibernate session, subsequent attempts to modify the collection threw up the mentioned exception.

    Changing the scope of the JSF managed bean seems to solve the issue.

    I hope this helps.

    Comment by yuguuk | May 20, 2008

  3. still missing the explanation. I can say I solved something without saying how… that’s too easy…

    Comment by jack | November 6, 2008

  4. [...] from imma [...]

    Pingback by Common Hibernate Errors and Causes | Lam Nguyen’s Blog | December 20, 2008

  5. I am using NHibernate2.1… i got solved this issue when i use session.Merge() instead of session.update()/session.SaveorUpdate()

    hope this heps some one..

    ibrahim(SCPL)

    Comment by Ibrahim | November 24, 2009

  6. Ibrahim, this solution saved me, using merge instead of saveOrUpdate. I use zk + hibernate. I managed to make it work only when using lazy-loading = false. However, when I tried to use lazy loading, many exceptions occured: either two sessions were open, or there was no session at all. I really don’t understand the matter in depth, it has to do with sessions, threads and requests, but it is beyond my understanding for the moment.

    Thanks anyway

    Comment by Alex Grigoriadis | December 3, 2009


Leave a comment