I ran into a slightly different problem, maybe it can help someone, and maybe it can help in solving this problem.
I think the above problem could be avoided by combining the objects in a new transaction, and then apply the .merge () method to the collection, causing the problem.
At first, I think the code above looks like this (I added comments to explain):
Machine.withTransaction { // transaction 1 // some code to add Parts yourEntity.addToParts(...) // some code to remove Parts Machine.withNewTrasaction { // transaction 2 // some code to remove Parts. yourEntity.removeFromParts(...) } // end of transaction 2 -> the session is flushed, and the transaction is committed // during the flush, hibernate detect that "parts" collection is already attached // to another session, in another transaction then throw "Illegal // attempt to associate a collection with two open sessions" // some code to update couple of columns in machine table. }
Then the solution is to combine the collection with a new transaction, it gives us something like this:
Machine.withTransaction { // transaction 1 // some code to add Parts yourEntity.addToParts(...) // some code to remove Parts Machine.withNewTrasaction { // transaction 2 // some code to remove Parts. yourEntity.removeFromParts(...) // Merging the collection to the session yourEntity.merge() // I haven't tried but maybe you need ensure // there is a merge cascade on "parts" collection } // end of transaction 2 -> the session is flushed, and the transaction is committed // some code to update couple of columns in machine table. }
In my case, when merging a new transaction, I solved the error message "Another object with the same identifier value was already associated with the session: [yourPackage.YourEntity]" (when I talk about YourEntity, you can also read YourDomaineClass)
source share