2012-12-03 18 views
2

刪除雙向關聯在我的域模型有很多的雙向關聯(包括一對多和多對多)JPA從反側

我讀過this article並取得樣本模式的基礎上,我的所有關聯的。 (ManyToMany協會有一個雙向addXY方法,遵循該模式)

使用the pattern in this article問題是,從反面刪除?

實施例:

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); 
} 

的問題是,該刪除前方法導致ConcurrentException。如何處理這個? 目標是要刪除CustomerStatus,並將所有客戶設置爲NULL,在那裏有該狀態。

UPDATE

沒有刪除前的方法,我已經得到了MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails

回答

2

不能調用this.customers.remove(C),而你是遍歷集合客戶。這個問題已經到來之前,所以你可能會發現其他的解決方案,在這裏: How to avoid ConcurrentModificationException when iterating over a map and changing values?

但一個簡單的解決方法就是創建一個從舊的一個新的列表來遍歷上刪除前:

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