How to delete child in hibernate when relationship is from child to parent

被刻印的时光 ゝ 提交于 2020-01-06 05:41:08

问题


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.

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.


回答1:


I will provide the example to a similar situation, applying which to your situation will solve the problem.

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;
}

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;
} 

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.



来源:https://stackoverflow.com/questions/10957500/how-to-delete-child-in-hibernate-when-relationship-is-from-child-to-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!