Hibernate 中的循环关系
我想在休眠中映射一棵树,但由于循环引用(关系不是双向的)而持久化它会导致异常。
class Node {
@ManyToOne
Node parent;
@OneToOne
Node leftChild;
@OneToOne
Node rightChild;
}
节点 N 引用其左子节点 L,后者又再次引用 N 作为其父节点。此外,节点 N 引用其右子节点 R,而右子节点 R 又再次将 N 引用为父节点。但是,我无法使关系成为双向的,因为父级将是左子级和右子级的相反。使该模型持久的最佳方法是什么?
问候, 约亨
I want to map a tree in hibernate, but persisting it results in an exception because of the cyclic reference (the relationships are not bidirectional).
class Node {
@ManyToOne
Node parent;
@OneToOne
Node leftChild;
@OneToOne
Node rightChild;
}
Node N references its left child L which in turn references N again as its parent. Also, node N references its right child R which in turn again references N again as parent. However, I cannot make the relationships bidirectional, because parent would be the inverse of both leftChild and rightChild. What is the best way to make this model persistable?
Regards,
Jochen
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我没有看到问题:
I don't see the problem:
在你的例子中,Hibernate 无法区分左右孩子。无论 Hibernate 如何,给定数据库中引用父级的两行,如何区分左行和右行?因此,如果同一个表中有多个引用父节点的条目,则实际上有从父节点到子节点的
OneToMany
。因此,我建议您将其建模为@OneToMany
。然后,如果有必要,提供一些瞬态 getter,通过一些额外的逻辑来区分子列表中的左子元素和右子元素。There is no way for Hibernate to distinguish left and right child in your example. Regardless of Hibernate, given two rows in the database that have reference to parent, how do you distinguish left and right? So, if you have multiple entries in the same table that refer to parent, you are actually having
OneToMany
from parent to children nodes. Therefore, I recommend that you model it as@OneToMany
. Then, if necessary, provide some transient getters that will distinguish left child vs right child in the list of children via some additional logic.