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
的两个集合,但这似乎是一个错误,我没有做不寻常的事情……
从Parent
或AnotherParent
中删除FetchType.EAGER
可以解决这个问题,但我需要它,所以真正的解决方案是使用@LazyCollection(LazyCollectionOption.FALSE)
而不是FetchType
(感谢Bozho的解决方案)。
发布于 2010-12-02 21:30:31
我认为更新版本的hibernate (支持JPA2.0)应该能处理这个问题。但除此之外,您可以通过使用以下命令注释集合字段来解决此问题:
@LazyCollection(LazyCollectionOption.FALSE)
记住要从@*ToMany
注释中删除fetchType
属性。
但请注意,在大多数情况下,Set<Child>
比List<Child>
更合适,所以除非确实需要List
,否则就使用Set
但是提醒一下,使用集合不会像Vlad Mihalcea in his answer所描述的那样消除底层的笛卡尔乘积!
发布于 2011-05-03 13:55:07
只需将List
类型更改为Set
类型。
但是提醒一下,你的不会像Vlad Mihalcea in his answer描述的那样消除底层的笛卡尔乘积!
发布于 2011-11-29 18:46:03
将Hibernate特定的@Fetch注释添加到代码中:
@OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
private List<Child> childs;
这应该会解决与Hibernate bug HHH-1718相关的问题
https://stackoverflow.com/questions/4334970
复制相似问题