Hibernate and parent/child relations
Posted
by Marco
on Stack Overflow
See other posts from Stack Overflow
or by Marco
Published on 2010-04-01T20:24:36Z
Indexed on
2010/04/01
20:33 UTC
Read the original article
Hit count: 353
Hi to all,
I'm using Hibernate in a Java application, and i feel that something could be done better for the management of parent/child relationships.
I've a complex set of entities, that have some kind of relationships between them (one-to-many, many-to-many, one-to-one, both unidirectional and bidirectional). Every time an entity is saved and it has a parent, to estabilish the relationship the parent has to add the child to its collection (considering a one-to-may relationship). For example:
Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);
session.save(c);
session.flush();
In the same way, if i remove a child then i have to explicitly remove it from the parent collection too.
Child c = (Child) session.load(Child.class, cid);
session.delete(c);
Parent p = (Parent) session.load(Parent.class, pid);
p.getChildren().remove(c);
session.flush();
I was wondering if there are some best practices out there to do this jobs in a different way: when i save a child entity, automatically add it to the parent collection. If i remove a child, automatically update the parent collection by removing the child, etc.
For example,
Child c = new Child();
c.setParent(p);
session.save(c); // Automatically update the parent collection
session.flush();
or
Child c = (Child) session.load(Child.class, cid);
session.delete(c); // Automatically updates its parents (could be more than one)
session.flush();
Anyway, it would not be difficult to implement this behaviour, but i was wondering if exist some standard tools or well known libraries that deals with this issue. And, if not, what are the reasons?
Thanks
© Stack Overflow or respective owner