hibernate @ManyToMany双向渴望提取 [英] hibernate @ManyToMany bidirectional eager fetching

查看:431
本文介绍了hibernate @ManyToMany双向渴望提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我认为应该很常见的问题,但我找不到答案。



我有2个对象:Group和User。我的课程如下所示:

  class Group 
{
@ManyToMany(fetch = FetchType.EAGER )
列表<用户>用户;
}

class User
{
@ManyToMany(fetch = FetchType.EAGER)
List< Group>组;

$ / code>

现在,当我尝试从数据库中获取用户时,团体和所有团体带来所有用户等等。最后,我得到了一个stackoverflow例外。



我该如何解决这个问题,仍然有我的双向关联和到达列表中对象的能力 p>

解决方案

如果您将双向关联的一侧设置为拥有侧,您是否遇到同样的问题关联使用 mappedBy 属性(您应该继续使用)?像这样:

  @Entity public class Group {
...
@ManyToMany(fetch = FetchType .EAGER,mappedBy =groups)
List< User>用户;
}

@Entity public class User {
...
@ManyToMany(fetch = FetchType.EAGER)
List< Group>组;
}

更新:我找不到任何证据在双向关联的两端使用 EAGER 取回是禁止的并且AFAIK,在Hibernate文档和/或JPA规范中没有提到这种限制。实际上,根据 com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_25378rel =noreferrer>此评论从Emmanuel Bernard到(某种程度上相似)的问题:


LAZY EAGER 应该与无限循环问题正交在代码库中。 Hibernate知道如何处理循环图

对于我来说,上述内容非常清晰,Hibernate应该能够处理您的映射(就像我在评论中提到),我会试图将任何相互矛盾的行为视为一个错误。



如果您可以提供允许重现问题的测试用例,我的建议是打开问题。


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?

解决方案

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:

@Entity public class Group {
  ...
  @ManyToMany(fetch = FetchType.EAGER, mappedBy="groups")
  List<User> users;
}

@Entity public class User {
  ...
  @ManyToMany(fetch = FetchType.EAGER)
  List<Group> groups;
}

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:

LAZY or EAGER should be orthogonal to an infinite loop issue in the codebase. Hibernate knows how to handle cyclic graphs

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 @ManyToMany双向渴望提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆