'Can orphanRemoval be used for depth > 1?

Should all child1 and child2 (depth 2) be deleted, when a parent gets deleted?

Database is Informix, constraints are created in the child tables. Deletion of parent is performed with JpaRepository.deleteById(parent.getId()), both do nothing and no error message occurs (show_sql just lists selects). Spring version is 5.3.19, spring-data-jpa 2.6.4.

Current example code:

@Entity
@Table(name = "parent_table")
public class Parent
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "parent", fetch = FetchType.EAGER)
    private Set<Child1> children = new HashSet<>();
}

@Entity
@Table(name = "child1_table")
public class Child1
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "parentid", referencedColumnName = "id", nullable = false)
    private Parent parent;

    @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "child1", fetch = FetchType.EAGER)
    private Set<Child2> children = new HashSet<>();
}

@Entity
@Table(name = "child2_table")
public class Child2
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "child1id", referencedColumnName = "id", nullable = false)
    private Child1 child1;
}

Update

added

@PreRemove
private void deleteChildren()
{
    children.clear();
}

to Parent and Child1. Now children get deleted, but not the Parent.



Solution 1:[1]

In fact, Parent also had a parent and I had to remove this from it's Set too.

So the solution is:

Clear children Sets

@PreRemove
private void preRemove()
{
    children.clear();
}

Remove the root entity from its parent in case it has a parent

@PreRemove
private void preRemove()
{
    children.clear();
    parentsParent.getParents().remove(this);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gunnar