hibernate @ManyToMany 双向急切获取
我有一个我认为应该很常见的问题,但我找不到答案。
我有 2 个对象:组和用户。我的类看起来像这样:
class Group
{
@ManyToMany(fetch = FetchType.EAGER)
List<User> users;
}
class User
{
@ManyToMany(fetch = FetchType.EAGER)
List<Group> groups;
}
现在,当我尝试从数据库中获取用户时,它会带来其所有组,所有组都会带来其所有用户,依此类推。最后,我得到了一个 stackoverflow 异常。
我怎样才能解决这个问题,同时仍然拥有双向关联并能够访问列表中的对象?
I have a question which I think should be pretty common but I can't find an answer.
I have 2 objects: Group and User. My classes look something like this:
class Group
{
@ManyToMany(fetch = FetchType.EAGER)
List<User> users;
}
class User
{
@ManyToMany(fetch = FetchType.EAGER)
List<Group> groups;
}
Now, when I try to get a User from the database it brings all its groups and all groups bring all its users and so on. Finally, I'm getting a stackoverflow exception.
How can I solve this issue and still have my bidirectional association and the ability to reach the objects in the lists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用
mappedBy
属性(您无论如何都应该使用)将双向关联的一侧作为关联的拥有一侧,您是否会遇到同样的问题?像这样:更新: 我找不到任何证据表明禁止在双向关联的两侧使用
EAGER
获取,据我所知,没有提到这样的限制在 Hibernate 文档和/或 JPA 规范中。实际上,根据 Emmanuel Bernard 对一个(某种程度上相似)问题的评论:
对我来说,上面的内容非常清楚,Hibernate 应该能够处理您的映射(正如我在评论中提到的),并且我很想将任何矛盾的行为视为错误。
如果您可以提供一个可以重现问题的测试用例,我的建议是提出一个问题。
Do you get the same problem if you make one of the sides of your bidirectional assocation the owning side of the association using the
mappedBy
attribute (that you should use anyway)? Like this:Update: I can't find any evidence that using
EAGER
fetching on both sides of a bidirectional association is forbidden and AFAIK, there is no mention of such a restriction in the Hibernate documentation and / or the JPA specification.Actually, according to this comment from Emmanuel Bernard to a (somehow similar) issue:
For me, the above is pretty clear, Hibernate should be able to handle your mapping (as I mentioned in a comment) and I would be tempted to consider any contradictory behavior as a bug.
If you can provide a test case allowing to reproduce the problem, my suggestion would be to open an issue.
当 Hibernate 尝试急切地获取它需要的所有内容时,它可以正常工作。建模对象必须考虑休眠,这样循环和 stackoverflow 异常就不会发生。
我所做的就是消除关系的一侧。您可以决定是否要删除该侧或保留它并将另一侧定义为所有者。您还需要从该侧删除急切的获取。
如果 hibernate 能够提供一种机制来定义多对多关系中的获取深度,那就太好了。
Hibernate works ok when it tries to eagerly fetch everything it needs to. Modeling objects has to take hibernate into account so loops and stackoverflow exceptions won't occur.
What i did is removing one side of the relationship. You can decide if you want to remove that side or to leave it and define the other side as the owner. You'll also need to remove the eager fetching from that side.
It would be nice if hibernate could give a mechanism for defining the depth of fetching in many-to-many relationships.
您可能需要将属性“hibernate.max_fetch_depth”设置为 3 之类的值以限制急切获取。
You might want to set the property "hibernate.max_fetch_depth" to something like 3 to limit eager fetching.