簡體   English   中英

JPA 從反向刪除雙向關聯

[英]JPA deleting bidirectional association from inverse side

在我的領域模型中有很多雙向關聯(OneToMany 和 ManyToMany)

我已經閱讀了這篇文章並根據示例模式進行了所有關聯。 (ManyToMany 關聯具有雙面 addXY 方法,遵循模式)

使用本文中的模式,問題是,從反面刪除怎么樣?

例子:

public class Customer implements Serializable {

...

@ManyToOne()
private CustomerStatus customerStatus;


@PreRemove
public void preRemove(){
    setCustomerStatus(null);
}

public void setCustomerStatus(CustomerStatus customerStatus) {
    if(this.customerStatus != null) { this.customerStatus.internalRemoveCustomer(this); }
    this.customerStatus = customerStatus;
    if(customerStatus != null) { customerStatus.internalAddCustomer(this); }
}

另一方面:

public class CustomerStatus implements Serializable {

private static final long serialVersionUID = 1L;

@OneToMany(mappedBy="customerStatus")
private List<Customer> customers;

@PreRemove
public void preRemove(){
    for(Customer c : customers){
        c.setCustomerStatus(null); // this causes ConcurrentException
    }

}

public List<Customer> getCustomers() {
    return Collections.unmodifiableList(this.customers);
}

public void addCustomer(Customer c){
    c.setCustomerStatus(this);
}

public void removeCustomer(Customer c){
    c.setCustomerStatus(null);
}

void internalAddCustomer(Customer c){
    this.customers.add(c);
}

void internalRemoveCustomer(Customer c){
    this.customers.remove(c);
}

問題是, preRemove 方法導致ConcurrentException 如何處理? 目標是刪除 CustomerStatus,並將所有存在該狀態的客戶設置為 NULL。

更新

沒有 preRemove 方法,我有MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails

您不能在迭代客戶集合時調用 this.customers.remove(c)。 這個問題之前已經出現過,因此您可能會在這里找到其他解決方案: 如何在迭代地圖和更改值時避免 ConcurrentModificationException?

但一個簡單的解決方案是從舊列表中創建一個新列表以在 preRemove 上迭代:

public void preRemove(){
    List<Customer> tempList = new ArrayList(customers);
    for(Customer c : tempList){
        c.setCustomerStatus(null); 
    }
}

暫無
暫無

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

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