gpt4 book ai didi

java - JPA级联都导致完整性约束

转载 作者:行者123 更新时间:2023-12-01 04:33:13 25 4
gpt4 key购买 nike

我有三个表:员工、老板和地址。

在本例中,员工和老板共享相同的地址。当我对 Employee 调用 EntityManager.remove 时,我收到完整性约束异常,因为它尝试删除地址,但它不能删除,因为老板仍然需要它。如果没有人使用该地址,我希望将其删除。我的注释应该是什么样子,以便我可以从 Address 中删除孤立的注释,同时避免完整性约束?

异常=

Internal Exception: java.sql.SQLIntegrityConstraintViolationException: DELETE on
table 'Employee' caused a violation of foreign key constraint 'Boss....

代码=

public class Employee {
@OneToMany(targetEntity = Address.class, orphanRemoval = true,cascade = {
CascadeType.ALL
} fetch=FetchType.EAGER)
@JoinTable(name = "Employee_Address")
@XmlElement(required = true)
@OrderColumn
protected List<Address> addresses;

}
public class Boss {

@OneToMany(targetEntity = Address.class, orphanRemoval = true, cascade = {
CascadeType.ALL
}fetch=FetchType.EAGER)
@JoinTable(name = "Boss_Address")
@XmlElement(required = true)
@OrderColumn
protected List<Address> addresses;
}

地址类对老板或员工一无所知。

最佳答案

您的注释是正确的。删除员工时,它将尝试删除其地址。

但如果两者使用相同的地址,删除将会失败。

考虑到这种情况,请使用不带 CasacadeType.DELETE 或 CasacadeType.ALL 的级联选项列表,并以编程方式解决问题。

也不要在此使用 orphanRemoval 。请参阅 JPA 2.0 规范,第 2.9 节:

If an entity that is the target of the relationship is removed from the relationship (by setting the relationship to null or removing the entity from the relationship collection), the remove operation will be applied to the entity being orphaned. The remove operation is applied at the time of the flush operation. The orphanRemoval functionality is intended for entities that are privately "owned" by their parent entity. Portable applications must otherwise not depend upon a specific order of removal, and must not reassign an entity that has been orphaned to another relationship or otherwise attempt to persist it. If the entity being orphaned is a detached, new, or removed entity, the semantics of orphanRemoval do not apply.

If the remove operation is applied to a managed source entity, the remove operation will be cascaded to the relationship target in accordance with the rules of section 3.2.3, (and hence it is not necessary to specify cascade=REMOVE for the relationship).

关于java - JPA级联都导致完整性约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17708687/

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