4

Consider class Parent:

{
    ...
    @OneToMany(cascade=CascadeType.ALL,mappedBy = "parent")
    Set<Child> children;
    ...
}

And class Child:

{
    ...
    @ManyToOne
    @JoinColumn(name="parentID")
    Parent parent;
    ...
}

If I create a new child inside of the application and put it inside the children field of the Parent, and then persist the Parent object, why doesn't Hibernate automatically update the parent field (in order to set the parentID column) of the Child object?

user42768
  • 1,951
  • 11
  • 22

1 Answers1

3

Because Hibernate isn't a magic tool. It is designed to use POJOs, that you design and write, and it doesn't modify the byte-code of those POJOs. It's your responsibility to initialize the other side of the association if you need to.

Another reason is that this is how the JPA specifications, that it must respect, specifies how it works.

But nothing prevents you from having a method

public void addChild(Child c) {
    this.children.add(c);
    c.parent = this;
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    It wouldn't have to modify the byte-code. Couldn't it just verify, when the parent object is saved, whether **children** is "populated" and if so to update the reference from inside the child? – user42768 Apr 02 '16 at 15:31
  • How would it decide that your intention is to have the child be added to the parent or not, since both objects don't tell the same thing? The parent says: yes, this is one of my children. The child says: no, I don't have any parent. So, who should Hibernate believe? The child or the parent? The specification has decided: it must believe the owner of the association, which is the child. – JB Nizet Apr 02 '16 at 15:35
  • I did think of that case, but I considered that the "logical" owner of the association should be believed. I now realize that this approach could cause serious problems. Thank you! – user42768 Apr 02 '16 at 15:42
  • the code you show above is this for uni directional relationships or bidirectional? Excuse me if my question is too trivial, I started with hibernate/JPA/Springboot this week. – Asma Rahim Ali Jafri Oct 04 '19 at 08:26
  • 1
    @AsmaRahimAliJafri you should be able to figure that out by yourself: If there are two sides in the relationship, and if the code shows that `this` has children, and that `children have a parent which is `this`, then by definition, it's a bidirectional association. If it was unidirectional, either the children wouldn't have a parent (it would thus be a unidirectional OneToMany from parent to children), or the parent wouldn't have children (it would thus be a unidirectional ManyToOne from child to parent). – JB Nizet Oct 04 '19 at 08:32