开发者

Hibernate and parent/child relations

开发者 https://www.devze.com 2022-12-25 04:01 出处:网络
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'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 (coul开发者_StackOverflow社区d 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号