net.sf.hibernate.LazyInitializationException: Illegally attempted to associate a proxy with two open Sessions

Hibernate JIRA | Peter Mutsaers | 1 decade ago
tip
Click on the to mark the solution that helps you, Samebug will learn from it.
As a community member, you’ll be rewarded for you help.
  1. 0

    1. Object obj = s1.get(someclass, someid); 2. s1.clear(); // or s1.evict(obj); in another thread: 3. s2.lock(obj, LockMode,NONE); The s2.lock() results in: net.sf.hibernate.LazyInitializationException: Illegally attempted to associate a proxy with two open Sessions at net.sf.hibernate.proxy.LazyInitializer.setSession(LazyInitializer.java:152) at net.sf.hibernate.impl.SessionImpl.reassociateProxy(SessionImpl.java:1027) at net.sf.hibernate.impl.SessionImpl.unproxyAndReassociate(SessionImpl.java:1011) at net.sf.hibernate.impl.SessionImpl.lock(SessionImpl.java:1709) Looking in LazyInitializer.setSession() I see: if ( session!=null && session.isOpen() ) { //TODO: perhaps this should be some other RuntimeException... throw new LazyInitializationException("Illegally attempted to associate a proxy with two open Sessions"); Indeed s1 is still open and the session field of the evicted object is not cleared, even when it is detached from s1. However the text of the exception is not quite accurate, since formally the object after s1.clear() is no longer associated with the first session. Hibernate falsely assumes here that as long as the session is open, the object is associated, as if no s1.evict() or s1.clear() had been taken place. According to the "Hibernate in action" book on page 116 section 4.1.1 an object is detached by session close/clear/evict, no difference is made between these. Now it seems that this is not fully the case. Should not the object(s) evicted/cleared from the session have their session field set to null? As it is, we can only move an object into another session if the first session has been fully closed.

    Hibernate JIRA | 1 decade ago | Peter Mutsaers
    net.sf.hibernate.LazyInitializationException: Illegally attempted to associate a proxy with two open Sessions

    Root Cause Analysis

    1. net.sf.hibernate.LazyInitializationException

      Illegally attempted to associate a proxy with two open Sessions

      at net.sf.hibernate.proxy.LazyInitializer.setSession()
    2. net.sf.hibernate
      SessionImpl.lock
      1. net.sf.hibernate.proxy.LazyInitializer.setSession(LazyInitializer.java:152)
      2. net.sf.hibernate.impl.SessionImpl.reassociateProxy(SessionImpl.java:1027)
      3. net.sf.hibernate.impl.SessionImpl.unproxyAndReassociate(SessionImpl.java:1011)
      4. net.sf.hibernate.impl.SessionImpl.lock(SessionImpl.java:1709)
      4 frames