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


当前回答

我们尝试了Set而不是List,这是一个噩梦:当您添加两个新对象时,equals()和hashCode()无法区分它们!因为他们没有任何身份证明。

典型的工具如Eclipse从数据库表中生成这种代码:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((id == null) ? 0 : id.hashCode());
    return result;
}

您还可以阅读这篇文章,它正确地解释了JPA/Hibernate是多么混乱。读完这篇文章后,我想这是我一生中最后一次使用ORM了。

我也遇到过领域驱动设计的人,他们说ORM是一个可怕的东西。

其他回答

我发现了一篇关于Hibernate在这种对象映射中的行为的很好的博文:http://blog.eyallupu.com/2010/06/hibernate-exception-simultaneously.html

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

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

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

我通过注释来解决:

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

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

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

简单地从列表类型更改为设置类型。

但请记住,你不会消除Vlad Mihalcea在他的回答中所描述的底层笛卡尔积!