Set null on cascading delete

916 views Asked by At

There are three tables, t1, t2 and t3. t1 is referenced by t2.fk2, and t2 is referenced by t3.fk3. The first relationship is set Cascading.ALL, so removing one row of t1 will delete one related row of t2 at the same time. But how to set null of t3 on delete t2? (t2 can be directly removed, and cascaded removal from t1's delete).

This can be easily done in MySQL, but in JPA I really don't know what to do. I looked for answers, and @PreRemove, orphanRemoval=true can solve my problem?

Thanks a billion!!

1

There are 1 answers

0
frogcdcn On

Manually setting fields to null works, e.g, t2.getT3XXField().setT2XXField(null).

You can also use @PreRemove callback in t2 to do this.

@PreRemove
public void preRemove(){

    T3Field.setT2Field(null);
}

Both ways work. Also, do not use Cascade.ALL or REMOVE on t2 for t3, because removing t2 will remove t3 entity, but in this scenario we don't want to set t3 null.