2

在我的域模型中有很多双向关联(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

4

1 回答 1

2

在迭代客户集合时,不能调用 this.customers.remove(c)。这个问题之前出现过,因此您可能会在此处找到其他解决方案: How to Avoid ConcurrentModificationException when iterate over a map and changed values?

但一个简单的解决方案是从旧列表创建一个新列表以在 preRemove 上进行迭代:

public void preRemove(){
    List<Customer> tempList = new ArrayList(customers);
    for(Customer c : tempList){
        c.setCustomerStatus(null); 
    }
}
于 2012-12-03T20:20:27.830 回答