我遇到一個稍微不同的問題,也許它可以幫助別人,也許它可以幫助上述問題。
我認爲上述問題可以通過合併實體到新事務來避免,然後在導致問題的集合上使用.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.
}
在我的情況,與所述新事務的合併,我解決了錯誤消息「A不同的對象使用相同的標識符值已經與會話相關聯:[yourPackage.YourEntity]」(當我跟關於YourEntity,你也可以閱讀YourDomaineClass)
你可以嘗試使用'Machine.withNewTransaction(傳播:TransactionDefinition.PROPAGATION_REQUIRES_NEW){...}'? – dmahapatro
@dmahapatro我回來錯誤爲'沒有方法的簽名:Machine.withNewTransaction'我覺得語法或錯誤的東西。我無法找到良好的文檔也爲這個 – user2001627