少し異なる問題に遭遇しました。おそらく誰かを助けることができ、上記の問題を解決できるかもしれません。
上記の問題は、エンティティを新しいトランザクションにマージし、問題の原因となっているコレクションで .merge() メソッドを使用することで回避できると思います。
まず、上記のコードは次のようになると思います (説明のためにコメントを追加しました)。
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.
}
解決策は、コレクションを新しいトランザクションにマージすることです。これにより、次のような結果が得られます。
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.
}
私の場合、新しいトランザクションのマージで、「同じ識別子の値を持つ別のオブジェクトが既にセッションに関連付けられていました: [yourPackage.YourEntity]」というエラー メッセージを解決しました (YourEntity について話すときは、次のことも読むことができます)。あなたのドメインクラス)