Hibernate在创建SessionFactory时抛出这个异常:

multiplebagfetchexception:不能同时获取多个包

这是我的测试用例:

Parent.java

@Entity
public Parent {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private Long id;

 @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
 // @IndexColumn(name="INDEX_COL") if I had this the problem solve but I retrieve more children than I have, one child is null.
 private List<Child> children;

}

Child.java

@Entity
public Child {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private Long id;

 @ManyToOne
 private Parent parent;

}

这个问题怎么样?我该怎么办?


EDIT

好的,我的问题是,另一个“父”实体是在我的父,我的真实行为是这样的:

Parent.java

@Entity
public Parent {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private Long id;

 @ManyToOne
 private AnotherParent anotherParent;

 @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
 private List<Child> children;

}

AnotherParent.java

@Entity
public AnotherParent {

 @Id
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 private Long id;

 @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
 private List<AnotherChild> anotherChildren;

}

Hibernate不喜欢FetchType有两个集合。EAGER,但这似乎是一个bug,我没有做不寻常的事情…

删除FetchType。来自Parent或AnotherParent的渴望解决了这个问题,但我需要它,所以真正的解决方案是使用@LazyCollection(LazyCollectionOption.FALSE)而不是FetchType(感谢Bozho的解决方案)。


当前回答

当你有一个太复杂的对象和一个简单的收集不是一个好主意,所有的对象都用EAGER fetchType,最好使用LAZY,当你真的需要加载集合使用:Hibernate.initialize(parent.child)来获取数据。

其他回答

我发现了一篇关于Hibernate在这种对象映射中的行为的很好的博文:http://blog.eyallupu.com/2010/06/hibernate-exception-simultaneously.html

对我来说,问题是嵌套了EAGER取回。

一种解决方案是将嵌套字段设置为LAZY,并使用Hibernate.initialize()来加载嵌套字段:

x = session.get(ClassName.class, id);
Hibernate.initialize(x.getNestedField());

在你的代码中添加一个hibernate特有的@Fetch注释:

@OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
private List<Child> childs;

这应该可以修复与Hibernate bug HHH-1718相关的问题

在我这边,当我使用FetchType有多个集合时就发生了这种情况。热切的,像这样:

@ManyToMany(fetch = FetchType.EAGER, targetEntity = className.class)
@JoinColumn(name = "myClass_id")
@JsonView(SerializationView.Summary.class)
private Collection<Model> ModelObjects;

此外,集合连接在同一列上。

为了解决这个问题,我将其中一个集合更改为FetchType。LAZY,因为它适合我的用例。

古德勒克! ~ J

关于@LazyCollection(LazyCollectionOption.FALSE)的一个好处是,在FetchType时,几个带有此注释的字段可以共存。即使在这种共存是合法的情况下,EAGER也不能。

例如,一个订单可能有一个OrderGroup列表(一个短的)以及一个促销列表(也是短的)。@LazyCollection(LazyCollectionOption.FALSE)可以同时使用,而不会导致LazyInitializationException和MultipleBagFetchException。

在我的情况下@Fetch确实解决了我的MultipleBacFetchException问题,但随后导致LazyInitializationException,臭名昭著的无会话错误。