Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

Hibernate throws this exception during SessionFactory creation:

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

This is my test case:

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;

}

How about this problem? What can I do?

EDIT

OK, the problem I have is that another "parent" entity is inside my parent, my real behavior is this:

Parent.java

@Entity

public Parent {

 @Id

 @GeneratedValue(strategy=GenerationType.IDENTITY)

 private Long id;

 @ManyToOne

 private AntoherParent anotherParent;

 @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)

 private List<Child> children;

}

AnotherParent.java

@Entity

public AntoherParent {

 @Id

 @GeneratedValue(strategy=GenerationType.IDENTITY)

 private Long id;

 @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)

 private List<AnotherChild> anotherChildren;

}

Hibernate doesn't like two collections with FetchType.EAGER, but this seems to be a bug, I'm not doing unusual things...

Removing FetchType.EAGER from Parent or AnotherParent solves the problem, but I need it, so real solution is to use @LazyCollection(LazyCollectionOption.FALSE) instead of FetchType (thanks to Bozho for the solution).

1 Answer

0 votes
by (46k points)

You need to perform this in a newer version of hibernate ( JPA 2.0 or above). But contrarily you can work it almost by annotating the collection fields with:

@LazyCollection(LazyCollectionOption.FALSE)

Remember to remove the fetchType attribute from the @*ToMany annotation.

However note that in most examples a Set<Child> is more relevant than List<Child>, so except you really need a List - go for Set

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...