【发布时间】:2011-05-19 02:39:15
【问题描述】:
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 的解决方案)。
【问题讨论】:
-
我会问,您希望生成什么 SQL 查询来同时检索两个单独的集合?能够实现这些的 SQL 类型要么需要笛卡尔连接(可能非常低效),要么需要不相交列的 UNION(也很丑陋)。据推测,无法在 SQL 中以干净高效的方式实现这一点影响了 API 设计。
-
@ThomasW 这些是它应该生成的 sql 查询:
select * from master; select * from child1 where master_id = :master_id; select * from child2 where master_id = :master_id -
如果您有多个
List<child>并且为多个List<clield>定义了fetchType,您可能会收到类似的错误
标签: java hibernate jpa one-to-many bag