This is a minor problem, but it may help some of you out there. The error can occur from several reasons, but in this case it was due to bad use of cascade update. The exception I received was:

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
at org.hibernate.collection.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:410)
at org.hibernate.event.def.OnUpdateVisitor.processCollection(OnUpdateVisitor.java:40)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:101)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:61)
at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:55)
at org.hibernate.event.def.AbstractVisitor.process(AbstractVisitor.java:123)

The problem was due to a misuse of cascade update in one of the mappings. The field was declared as follows:

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = “user_id”)
public User getAuthor() {
return author;
}

Removing the cascade = CascadeType.ALL fixed the problem.
Conclusion: carefully use cascade updates as it may get you into trouble. Use it when business logic requires it. In the example below there was no need for it, so removing it was both business and programatically a good decision.

technorati tags:, , , ,

7 responses to “Illegal attempt to associate a collection with two open sessions

  1. >This is a minor problem, but it may help some of you out there.

    Yes ! Thanks !

    Now, we will think twice before choosing a CascadeType value ! We know that this CascadeType option is not only for decoration ;-)

    Thanks again to open our eyes !

  2. Great help was your blog on Illegal attempt to associate a collection with two open sessions. I was really struggling a hell to overcome this exception.

    Thanks a lot

Leave a Comment:

Your email address will not be published. Required fields are marked *