9

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

我有 2 个对象:组和用户。我的课程看起来像这样:

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

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

现在,当我尝试从数据库中获取用户时,它会带来它的所有组,所有组都会带来它的所有用户,依此类推。最后,我得到了一个 stackoverflow 异常。

我怎样才能解决这个问题,并且仍然有我的双向关联和访问列表中对象的能力?

4

3 回答 3

10

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.

于 2010-10-20T14:26:32.273 回答
0

您可能希望将属性“hibernate.max_fetch_depth”设置为 3 以限制急切获取。

于 2011-01-05T09:33:09.303 回答
0

当 Hibernate 尝试急切地获取所需的所有内容时,它可以正常工作。建模对象必须考虑休眠,因此不会发生循环和 stackoverflow 异常。

我所做的是消除关系的一方面。您可以决定是要删除该侧还是保留它并将另一侧定义为所有者。您还需要从那一侧删除急切的获取。

如果 hibernate 可以提供一种机制来定义多对多关系中的获取深度,那就太好了。

于 2010-10-28T09:51:29.957 回答