Illegal attempt to associate a collection with two open sessions

2 min read >

Illegal attempt to associate a collection with two open sessions

Engineering Insights & Enterprise solutions

This is a minor problem, but it may help some of you out there. The error can occur for several reasons, but in this case, it was due to the bad use of cascade updates. 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 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 they 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 programmatically a good decision.

technorati tags: java, hibernate, illegal, attempt, collection

Unlock innovation and digital transformation for your business.

Get in touch

We are always happy to talk

Phone

+40-21-223-7700

Email

hello@tremend.com

Address

165 Splaiul Unirii, Timpuri Noi Square,
TN Office 2 building, 4th floor,
District 3, Bucharest, Romania, 030134