Let's assume a simple 1 Father -> n Children entity relationship (getters/setters omitted):
@Entity
public class Father {
@Id
@GeneratedValue
private Integer id;
@OneToMany(mappedBy="father", cascade=CascadeType.ALL)
private List<Child> children = new ArrayList<>();
...
}
@Entity
public class Child {
@Id
@GeneratedValue
private Integer id;
@ManyToOne(cascade=CascadeType.ALL)
private Father father;
...
}
When now trying to update that relationship by simply adding a child to the father, it doesn't work, since Child.father
does not get updated:
Child child = new Child();
// optionally persist child first, tried
father.getChildren().add(child);
...save father
I tried using different CascadeTypes, but nothing seems to work to automatically update the Child.father
reference. I know that a traditional way would be to have an "addChild" method, but I would like the know if there is an automatic way to do so?
My configuration is Spring Boot + JPA (Hibernate) + H2, automatically creating to database. Interesting enough, I have found some blog postings that seem to do exactly what I do here, but for them it works, but not for me. Strange.