Announcement Announcement Module
No announcement yet.
Hibernate/Spring: Illegal attempt to associate a collection with two open sessions in Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hibernate/Spring: Illegal attempt to associate a collection with two open sessions in


    I am seeing the above error in my unit tests, and am at a loss how to correct it.

    My unit test class extends AbstractTransactionalDataSourceSpringContextTests and performs the following:

    	// Retrieve a RuleGroup
    	RuleGroup ruleGroupToUpdate = ruleGroupDao.findRuleGroup(a, b, c, d);
    	// Update an encapsulated Attribute
        // Save the RuleGroup
    The following is a snippet of my RuleGroup mapping file. As you can see, a RuleGroup has encapsulated Rule and Attribute collections, both of which are lazy loaded by default:

    <class name="a.b.c.d.RuleGroup" table="RULE_GROUP">
    		<id name="ruleGroupID" column="RULE_GRP_ID">
    			<generator class="increment"/>
    		<set name="rules" lazy="true" cascade="save-update" table=RULES">
    		 	<key column="RULE_GRP_ID" not-null="false"/>
    			<many-to-many unique="true" column="RULE_ID" class="a.b.c.d.Rule"/>
    		<set name="attributes" lazy="true" cascade="save-update" table="ATTRIBUTES">
    			<key property-ref="xrefID" column="XREF_ID" not-null="true"/>
    			<many-to-many unique="true" column="CONFIG_ATTR_ID" class="a.b.c.d.Attribute"/>				
    My DAO class extends HibernateDaoSupport:
    • The findRuleGroup method uses getSession().createCriteria() to perform the query. The rules and attributes are retrieved using a "join" fetch
    • The updateRuleGroup method uses getHibernateTemplate().update() to perform the update

    From debugging my test, a new Session is created in the findRuleGroup method, and then again in the updateRuleGroup method. Therefore, when the update is performed Hibernate sees that my Attribute collection is already associated with the findRuleGroup session and throws the exception.

    How do I resolve this? Presumably, the update should not open a new session. If I specify that HibernateTemplate should not create a new session, then I get a different exception saying there is no session associated with the thread. I am at a loss here!

  • #2
    Could you post the complete error stack trace? without that is not easy to see the cause problem


    • #3
      Make your test transactional, next to that you should really not use HibernateDaoSupport/HibernateTemplate as that should be considered deprecated (since about 2007).


      • #4
        Thanks for reply. I removed the deprecated AbstractTransactionalDataSourceSpringContextTests and switched to using Spring 3's annotation based unit testing.
        So once I did this, and annotated my test method with @Transactional the error no longer occurred.