gpt4 book ai didi

java - JPA从反面删除双向关联

转载 作者:行者123 更新时间:2023-11-30 09:29:14 25 4
gpt4 key购买 nike

在我的领域模型中有很多双向关联(OneToMany 和 ManyToMany)

我读过 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);
}

问题是 preRemove 方法会导致 ConcurrentException。如何处理?目标是删除 CustomerStatus,并将存在该状态的所有客户设置为 NULL。

更新

没有 preRemove 方法,我得到了 MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails

最佳答案

在遍历客户集合时不能调用 this.customers.remove(c)。这个问题之前已经出现过,所以你可以在这里找到其他解决方案: How to avoid ConcurrentModificationException when iterating over a map and changing values?

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

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

关于java - JPA从反面删除双向关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13687613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com