繁体   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