Spring Data. Delete child entity on deleting one of the parents

I need to delete my child entity if one of the parent are being removed.

Right now child entity will be removed if both parents are removed and I need to change the behaviour.

For example if you have:

class Parent1 {
    @Id
    Long id;
    
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    Set<Child> children = new HashSet();
}
class Parent2 {
    @Id
    Long id;
    
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    Set<Child> children = new HashSet();
}
class Child {
    @Id
    Long id;
    
    @ManyToOne
    Parent1 p1;

    @ManyToOne(fetch = FetchType.EAGER)
    Parent2 p2;
}

I tried to use some combinations with orphanRemoval, but it didn't work. Do you have any other suggestions?

1 answer

  • answered 2021-02-24 05:31 Jens Schauder

    I'd put this kind of logic simply in a method that removes a parent. It would then also remove the other parent. This method could live on the Child class or a separate service.

    Note, that currently your mapping is missing mappedBy values for the bidirectional relationships.