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