Here's my code:
Entities:
@Entity
public class A {
@Id
Long aId;
...
}
@Entity
public class B {
@Id
Long bId;
Long aId;
...
}
Service:
@Transactional
public void multiInsert() {
A a = createA();
aRepository.save(a);
B b = createBFromA();
bRepository.save(b);
}
When I am try to do bRepository.save(), it is failing with the following error:
Caused by: java.sql.SQLException: Cannot add or update a child row: a foreign key constraint fails (
b, CONSTRAINTa_to_bFOREIGN KEY (aId) REFERENCESa(aId))
My guess is a is not persisted before we are trying to save b due to which the foreign key constraint is failing.
I am aware that for foreign key, I should use @JoinColumns. But is there a way to make it work without that.