hibernatehibernate-cascade

Why doesn't Hibernate set the child's reference to the parent?


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?


Solution

  • 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;
    }