簡體   English   中英

持久化分離對象出錯“在同步過程中,通過未標記為級聯 PERSIST 的關系發現了一個新對象”

[英]Persisting detached object got error "during synchronization a new object was found through a relationship that was not marked cascade PERSIST"

during synchronization a new object was found through a relationship that was not marked cascade PERSIST: Wallet ...遇到錯誤during synchronization a new object was found through a relationship that was not marked cascade PERSIST: Wallet ...
我知道錯誤通常是由於您沒有CascadeType.PERSIST並且沒有專門保留該實體,但我的故事可能會有所不同,因為我確實保留了該實體。

我在交易中創建用戶,然后將用戶傳遞給新交易,在該交易中創建錢包並將其附加到用戶。
退出createUser函數時發生錯誤。
雖然我知道將托管對象傳遞給新事務並在那里進行更改是一個壞主意,但我希望代碼在 Spring 上下文中可以工作。 但我不確定為什么它會在 J2EE 中引發錯誤。

我還發現您可以通過在退出createUser之前執行以下操作之一來修復它

  1. 再次合並錢包,以便再次管理對象,或
  2. 再次從數據庫獲取新創建的錢包並將其附加到用戶。 所以當退出createUser ,它知道 wallet 不是一個新實體而是已經持久化了。

如果有人能告訴我 J2EE 和 Spring 之間有什么不同,這段代碼在前一個中不起作用,那將不勝感激。

// existing transaction 
public void createUser(){
        User user = userRepo.createUser();
        walletService.createAndAttachWalletToUser(user);
        // add to fix
        // user.setWallet(walletService.merge(user.getWallet())); OR
        // user.setWallet(walletService.getWallet(user.getWallet().getId()));
}

// WalletService class
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void createAndAttachWalletToUser(User user){
        Wallet wallet = walletRepo.createWallet();
        user.setWallet(wallet);
}

這個問題已經有一段時間沒有回答了,所以在這里發布漫游:

您可以通過在退出createUser之前執行以下操作之一來修復它

再次合並錢包以便再次管理對象,或者再次從數據庫獲取新創建的錢包並將其附加到用戶。 這樣當退出 createUser 時,它就知道 wallet 不是一個新實體而是已經持久化了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM