I have the following scenario:
class A {
@OneToMany(mappedBy = "a", cascade = {CascadeType.PERSIST})
List<B> bsOfA;
@OneToMany(mappedBy = "a", cascade = {CascadeType.PERSIST})
List<C> csOfA;
}
class B {
@OneToMany(mappedBy = "b", cascade = {CascadeType.PERSIST})
List<D> dsOfB;
@ManyToOne
A a;
}
class C {
@OneToMany(mappedBy = "c", cascade = {CascadeType.PERSIST})
List<D> dsOfC;
@ManyToOne
A a;
}
class D {
@ManyToOne
C c;
@ManyToOne
B b;
@ManyToOne
A a;
}
Then, I am attempting to save A along with all its associated entities as follows:
a = new A(aId);
b = new B(bId);
c = new C(cId);
d = new D(dId);
a.setBsOfA(List.of(b));
a.setCsOfA(List.of(c));
b.setDsOfB(List.of(d));
c.setDsOfC(List.of(d));
repo.save(a)
Now my problem is, I am getting a foreign key violation because the order of insertion is incorrect. Checking my logs, I am seeing the following order of insertion: a -> b -> d (error c not yet existing)
How can I enforce Hibernate to insert in the correct order: a -> b -> c -> d OR a -> c -> b -> d