views:

123

answers:

1

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

+4  A: 

One simple way to achieve this type of thing is to add convenience methods to your model classes to ensure that both directions of the bidirectional link are set

public class Parent {
    ...
    public void addChild(Child child) {
        this.getChildren.add(child);
        child.setParent(this);
    }

    public void removeChild(Child child) {
        this.getChildren.remove(child);
        child.setParent(null);
    }

This requires some discipline/remembrance on your part to use these methods instead of the direct set/add; but it's best to put commonly used code in a single place.

matt b
Strongly agree with this comment - encapsulate those operations.
John
+1; that's how we do this, too.
mindas