Search code examples
javajpaeclipselinkone-to-many

Can JPA handle deleting a parent object when the child is deleted?


I have a View entity object with an employee object and an address object. A view has a list of employees. An employee has a list of Addresses. I want to delete the employee. I am getting a constraint complaining about Deleting the View. The view should stay but the relationship between view and employee should be gone. Address should be gone too. Can anyone tell me how to set up my JPA to handle this case? Or should I just do it programatically. (Find all the views first and then delete the employees from the view).

View {
 @OneToMany(targetEntity = Employee.class, orphanRemoval = true)
@JoinTable(name = "View_Employee")
protected List<Employee> employees;
}

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

Address{
nothing of interest, no ties to view or employee
}

Solution

  • When you delete an object in JPA, you must first remove all references to it form your model.

    If you want to delete an Employee, first remove the Employee from all Views.

    For the address if you use @CascadeOnDelete, ensure you have set the constraint to cascade, otherwise remove this.