Issue
TL;DR: Is it enough to call repository.save()
on the owning entity to persist the relationship or do I need to save both entities?
Let's say I have two entities, A
and B
and a oneToMany relationship between them. A
can have multiple B
's, B
can have an A
. B
is the owning side of the relationship (has the foreign key). If I have two, already persisted entities and want to add and persist a relationship between them, then I typically do this:
a.addB(b);
b.setA(a);
bRepository.save(b);
My question is, do I also need to call aRepository.save(a)
? Thanks in advance, Googling didn't help me to find the answer.
Solution
If as you describe the relationship is owned by B
, A
didn't change at all as far as JPA is concerned. So it doesn't need to get persisted.
If you have persisted or loaded A
and B
in the current session, no save
at all is technically necessary. JPA keeps track of the entities, note that they are changed and will flush the changes to the database at the end of the transaction.
Answered By - Jens Schauder
Answer Checked By - David Goodson (JavaFixing Volunteer)