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的解决方案)。


当前回答

你可以使用一个新的注释来解决这个问题:

@XXXToXXX(targetEntity = XXXX.class, fetch = FetchType.LAZY)

实际上,fetch的默认值是FetchType。懒惰。

其他回答

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

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

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

同时注释Fetch和LazyCollection有时有助于运行项目。

@Fetch(FetchMode.JOIN)
@LazyCollection(LazyCollectionOption.FALSE)

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

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

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

你可以使用一个新的注释来解决这个问题:

@XXXToXXX(targetEntity = XXXX.class, fetch = FetchType.LAZY)

实际上,fetch的默认值是FetchType。懒惰。

我通过注释来解决:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)