MultipleBagFetchException thrown by Hibernate
Hibernate doesn't allow fetching more than one bag because that would generate a Cartesian product, and for unordered Lists, which are called baggs in Hibernate terminology, this will cause duplicate entries even if the underlying collection does not have those duplicated rows. So, Hibernate simply prevents this situation when the JPQL query is compiled.
Now, you will find lots of answers, blog posts, videos, or other resources telling you to use a Set
instead of a List
for your collections.
That's terrible advice. Don't do that!
Using Sets
instead of Lists
will make the MultipleBagFetchException
go away, but the Cartesian Product will still be there.
The right fix
Instead of using multiple JOIN FETCH
in a single JPQL or Criteria API query:
List<Post> posts = entityManager
.createQuery(
"select p " +
"from Post p " +
"left join fetch p.comments " +
"left join fetch p.tags " +
"where p.id between :minId and :maxId", Post.class)
.setParameter("minId", 1L)
.setParameter("maxId", 50L)
.getResultList();
You can do the following trick:
List<Post> posts = entityManager
.createQuery(
"select distinct p " +
"from Post p " +
"left join fetch p.comments " +
"where p.id between :minId and :maxId ", Post.class)
.setParameter("minId", 1L)
.setParameter("maxId", 50L)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.getResultList();
posts = entityManager
.createQuery(
"select distinct p " +
"from Post p " +
"left join fetch p.tags t " +
"where p in :posts ", Post.class)
.setParameter("posts", posts)
.setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.getResultList();
As long as you fetch at most one collection using JOIN FETCH
, you will be fine. By using multiple queries, you will avoid the Cartesian Product since any other collection but the first one is fetched using a secondary query.
This is a rather nasty problem in Hibernate and actually ORM in general.
What happens is that the many (fetch) joins cause a rather large cartesian product to be created. I.e for ever other join new columns and new rows appear in the result, leading to a (fairly) large 'square' result.
Hibernate needs to distill a graph from this table, but it's not smart enough to match the right columns to the right entities.
E.g.
Suppose we have the result
A B C
A B D
Which needs to become:
A
|
B
/\
C D
Hibernate could deduct from the primary keys and some encoding magic, what the graph must be, but in practice it needs explicit help to pull this off.
One way to do this is by specifying the Hibernate specific @IndexColumn
or the JPA standard @OrderColumn
on the relations.
E.g.
@Entity
public class Question {
@ManyToMany
@JoinTable(
name = "question_to_answer",
joinColumns = @JoinColumn(name = "question_id"),
inverseJoinColumns = @JoinColumn(name = "answer_id")
)
@IndexColumn(name = "answer_order")
private List<Answer> answers;
// ...
}
In this example I'm using a join table, with an extra column answer_order
. Via this column, which has a unique sequential number per Question/Answer relation, Hibernate can distinguish the entries in the result table and create the required Object graph.
One note btw, if it concerns more than a few entities, using so many eager joins can potentially lead to a much larger result set than you might think based on the number of entities involved.
Further reading:
- Hibernate Exception - Simultaneously Fetch Multiple Bags 1