我遇到了一个稍微不同的问题,也许它可以帮助某人,也许它可以帮助解决上述问题。
我认为可以通过将实体合并到新事务中来避免上述问题,然后在导致问题的集合上使用 .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 时,您还可以阅读你的域类)