0

I want to know why if I have a parent and child relation and want to add a child into a parent, it's not enough to set the parent of the child and have to add the child into the parent.

Parent parent = new Parent();
Child child = new Child();
child.setParent(parent);

// Why the next line?
parent.getChild().add(child);

isn't enough to set the parent of the child, and mark the relation of one-to-many to inverse ="true"?

Mohamed Ramadan
  • 475
  • 2
  • 7
  • 15

2 Answers2

1

take a look at this so-thread. If your mapping contains everything hibernate needs it would be enough to just set the parent. The answer in that thread also explains that all cached objects are also not updated and presents a solution for that.

Community
  • 1
  • 1
thomas
  • 5,637
  • 2
  • 24
  • 35
0

The last line is not strictly necessary. Hibernate uses the owner side (the child side in this case) to know if it has to persist the association.

However, it does not care if you initialized the other side, and won't do it for you. So, if this method happens to return the parent to the GUI, for example, the GUI will get a parent without the new child in its list of children. Similarly, it this code snippet is only a small part of a longer transaction, the rest of the code in the transaction won't see the new child in the children list, because you failed to maintain the coherence of the object graph.

So, unless this code is in a facade, and the parent is never used after this code snippet is executed, you should initialize both sides. If you know what you're doing, and you know that the parent will be out of scope, not used and garbage-collected after this code snippet, initializing only the owning side is sufficient. But remember that the session cache itself maintains a reference to the parent until the session is closed.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255