小编典典

Hibernate引发MultipleBagFetchException-无法同时获取多个包

hibernate

Hibernate在创建SessionFactory时抛出此异常:

org.hibernate.loader.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;

}

这个问题怎么样?我能做什么?


编辑

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

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,但这似乎是一个错误,我没有做不寻常的事情…

FetchType.EAGER从问题中删除ParentAnotherParent解决问题,但是我需要它,所以真正的解决方案是使用@LazyCollection(LazyCollectionOption.FALSE)而不是FetchType)。


阅读 316

收藏
2020-06-20

共1个答案

小编典典

我认为较新版本的hibernate(支持JPA 2.0)应该可以解决此问题。但是,否则,您可以通过以下方式对集合字段进行注释来解决:

@LazyCollection(LazyCollectionOption.FALSE)

请记住fetchType@*ToMany注释中删除该属性。

但是请注意,在大多数情况下,a Set<Child>比更为合适List<Child>,因此除非您确实需要List-Set

但是请记住,使用集 不会 消除VladMihalcea在其答案中描述的底层 Cartesian product

2020-06-20