Hibernate 在 SessionFactory 创建期间抛出这个异常:
org.hibernate.loader.MultipleBagFetchException:不能同时获取多个包
这是我的测试用例:
父类.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;
}
子.java
@Entity
public Child {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@ManyToOne
private 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;
}
另一个父母.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
的两个集合,但这似乎是一个错误,我没有做不寻常的事情……
从 Parent
或 AnotherParent
中删除 FetchType.EAGER
--- 可以解决问题,但我需要它,所以真正的解决方案是使用 @LazyCollection(LazyCollectionOption.FALSE)
FetchType
(感谢 Bozho 的解决方案)。
原文由 blow 发布,翻译遵循 CC BY-SA 4.0 许可协议
我认为更新版本的休眠(支持 JPA 2.0)应该处理这个问题。但除此之外,您可以通过以下方式注释集合字段来解决它:
请记住从
@*ToMany
注释中删除fetchType
属性。But note that in most cases a
Set<Child>
is more appropriate thanList<Child>
, so unless you really need aList
- go forSet
但请注意,使用集合 不会 消除 Vlad Mihalcea 在他的回答 中描述的底层 笛卡尔积!