I'd like to comment about a situation that happened with me today when I was using EclipseLink-JPA. I'll show what was the context and how I solved my issue, but I confess I do not understood what happened.
Consider the following mapping:
class A {
...
@OneToMany(mappedBy = "a")
@CascadeOnDelete
List<B> bs;
}
class B {
...
@ManyToOne(optional = false)
A a;
@OneToMany(mappedBy = "b")
@CascadeOnDelete
List<C> cs;
}
class C {
...
@ManyToOne(optional = false)
B b;
}
You can notice that there are "delete cascades" between classes A and B and between classes B and C. When I try to delete an object of the B class, everything is ok. However, when I try to delete an object of the A class, a key constraint violation exception occurs. If I ommit the list of C objects of the class B, all works well.
Is this a expected behavior of JPA?
To solve this issue, I created a SQL statement to delete all registers of table B, as may be noted bellow. However, I do not know if there is a more elegant solution.
delete from B b where b.a.id = :aid