问题描述
我试图在删除父项时删除子项记录。父表中没有引用子节点的列。孩子以一对一的可选关系引用父母。
I am trying to delete a child record when parent is deleted. There is no column in the parent table that refers to child. The child refers to parent in a one-to-one optional relationship.
当父项被删除时,由于事实关系依然存在,所以会引发一个约束。如果我将设置的关系添加到孩子侧,这没有帮助。 Hibernate不会删除子记录,因为我猜测,子记录永远不会被获取。
When parent is being deleted, a constraint is thrown due to the fact relationship still exists. If I add the set relationship to the child side, it does not help. Hibernate does not delete the child record since I am guessing, child record was never fetched.
有没有办法在拦截器中删除子记录?谢谢。
Is there a way to delete child records short of doing it in an interceptor ? Thanks.
推荐答案
我会举例说明类似的情况,应用哪种情况可以解决问题。
I will provide the example to a similar situation, applying which to your situation will solve the problem.
让我们假设Employee的表中有Department_ID,而Department没有任何引用Employee_ID的列。
Lets assume that Employee has a Department_ID in it's table, and Department does not have any column referencing Employee_ID.
我们使用加入列将员工与部门相关联。
We associate employee with a department using join column. This way we get uni-directional association.
public class Employee {
@OneToOne
@JoinColumn(name = "DEPARTMENT_ID")
private Department department;
}
接下来,我们通过将属性。它引用雇员方面的协会的拥有领域。
$ b
Next we associate department with employee by marking association with mappedBy
attribute. It references the owning field of the association on the Employee side. This way we get bi-directional association.
public class Department {
@OneToOne(mappedBy = "department", cascade = CascadeType.ALL)
private Employee employee;
}
标记与CascadeType.ALL的关联将包括CascadeType.REMOVE,它将级联到员工在删除操作。现在,删除部门,将随同它一起删除员工。
Marking association with CascadeType.ALL will include CascadeType.REMOVE, which will cascade to Employee on remove operation. Now, removing department, will remove employee along with it.
这篇关于如何在关系从小孩到父母的关系中删除hibernate中的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!