簡體   English   中英

有沒有辦法將分離的對象傳遞給JPA持久化? (傳遞給持久化的分離實體)

[英]Is there a way to pass detached object to JPA persist? (detached entity passed to persist)

我有2個實體: AccountAccountRole

public class Account {
   private AccountRole accountRole;

   @ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
   public AccountRole getAccountRole() {
      return accountRole;
   }

public class AccountRole {
    private Collection<Account> accounts = new ArrayList<Account>();

    @OneToMany(mappedBy = "accountRole", fetch = FetchType.EAGER)
    public Collection<Account> getAccounts() {
         return accounts;
    }

當我從數據庫中獲取accountRole並嘗試保留我的Account 此時我剛創建了我的帳戶,角色已經存在於db中。

AccountRole role = accountService.getRoleFromDatabase(AccountRoles.ROLE_USER);
account.setAccountRole(role);

//setting both ways, as suggested
public void setAccountRole(AccountRole accountRole) {
    accountRole.addAccount(this);
    this.accountRole = accountRole;
}

entityManager.persist(account); // finally in my DAO

我讀到這個: JPA / Hibernate:傳遞給persist的分離實體 我理解的是,我必須從兩個方向設置實體值,以便我在我的setter中做什么。

仍然有錯誤。

 org.hibernate.PersistentObjectException: detached entity passed to persist: foo.bar.pojo.AccountRole

只需更換

entityManager.persist(account);

有:

entityManager.merge(account);

並允許合並級聯:

@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.EAGER)
public AccountRole getAccountRole() {
    return accountRole;
}

因為合並這樣做:

如果您的實體是新實體,則它與persist()相同。 但是如果您的實體已經存在,它將更新它。

看起來您在處理期間離開了事務,因此accountRole被分離,或者由於其他原因已經分離。

在調用entityManager.merge(accountRole)之前調用entityManager.merge(accountRole) entityManager.persist(account)應該修復它。

編輯:不幸的是,如果您無法確定數據庫中是否已存在accountRole ,則必須通過查詢來檢查它。 如果存在 - 合並,如果不存在 - 繼續。 這確實很麻煩,但我還沒有看到更好的解決方法。

EDIT2:您傳遞給實體merge方法將保持斷開狀態-托管實體將被返回的merge ,所以你需要首先合並,然后在基准設置account到的返回值merge

你不能傳遞一個數據庫實體來堅持,沒有辦法。 但你不需要。

您希望獨立於AccountRole (已保留)持久保存Account 為了實現這一點,只需@ManyToOne中的@ManyToOne中刪除級聯 (在本例中為Account ):

public class Account {
    private AccountRole accountRole;

    @ManyToOne // no cascading here!
    public AccountRole getAccountRole() {
        return accountRole;
    }

請參閱我的解釋,原因如下: https//stackoverflow.com/a/54271569/522578

暫無
暫無

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

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