Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

10/3/2021 A Guide to MultipleBagFetchException in Hibernate | Baeldung

(/)

A Guide to
MultipleBagFetchException in
Hibernate
Last modi ed: January 17, 2021

by baeldung (https://www.baeldung.com/author/baeldung/)

Persistence (https://www.baeldung.com/category/persistence/)
Exception (https://www.baeldung.com/tag/exception/)
Hibernate (https://www.baeldung.com/tag/hibernate/)

The early-bird price of the new Learn Spring Data JPA


course is increasing by $35 on Friday:
>> GET ACCESS NOW (https://www.baeldung.com/learn-spring-
data-jpa-course#table)

1. Overview

https://www.baeldung.com/java-hibernate-multiplebagfetchexception 1/10
10/3/2021 A Guide to MultipleBagFetchException in Hibernate | Baeldung

In this tutorial, we'll talk about the MultipleBagFetchException


(https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/loader/
MultipleBagFetchException.html). We'll begin with the necessary terms to
understand, and then we'll explore some workarounds until we reach the ideal
solution.
We'll create a simple music app's domain to demonstrate each of the
solutions.

2. What is a Bag in Hibernate?


A Bag, similar to a List, is a collection that can contain duplicate elements.
However, it is not in order. Moreover, a Bag is a Hibernate (/jpa-hibernate-
di erence) term and isn't part of the Java Collections Framework.
Given the earlier de nition, it's worth highlighting that both List and Bag uses
java.util.List. Although in Hibernate, both are treated di erently. To di erentiate
a Bag from a List, let's look at it in actual code.
A Bag:

// @ any collection mapping annotation


private List<T> collection;

A List:

// @ any collection mapping annotation


@OrderColumn(name = "position")
private List<T> collection;

3. Cause of MultipleBagFetchException
Fetching two or more Bags at the same time on an Entity could form a
Cartesian Product. Since a Bag doesn't have an order, Hibernate would not be
able to map the right columns to the right entities. Hence, in this case, it
throws a MultipleBagFetchException.
Let's have some concrete examples that lead to MultipleBagFetchException.
https://www.baeldung.com/java-hibernate-multiplebagfetchexception 2/10
10/3/2021 A Guide to MultipleBagFetchException in Hibernate | Baeldung

For the rst example, let's try to create a simple entity that has 2 bags and
both with eager fetch type. An Artist might be a good example. It can have a
collection of songs and o ers.
Given that, let's create the Artist entity:

@Entity
class Artist {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

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


private List<Song> songs;

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


private List<Offer> offers;

// constructor, equals, hashCode


}

If we try to run a test, we'll encounter


a MultipleBagFetchException immediately, and it won't be able to build
Hibernate SessionFactory. Having that said, let's not do this.
Instead, let's convert one or both of the collections' fetch type to lazy:

@OneToMany(mappedBy = "artist")
private List<Song> songs;

@OneToMany(mappedBy = "artist")
private List<Offer> offers;

Now, we'll be able to create and run a test. Although, if we try to fetch both of
these bag collections at the same time, it would still lead to
MultipleBagFetchException.

4. Simulate a MultipleBagFetchException

https://www.baeldung.com/java-hibernate-multiplebagfetchexception 3/10
10/3/2021 A Guide to MultipleBagFetchException in Hibernate | Baeldung

In the previous section, we've seen the causes of MultipleBagFetchException.


Here, let's verify those claims by creating an integration test.
For simplicity, let's use the Artist entity that we've previously created.
Now, let's create the integration test, and let's try to fetch
both songs and o ers at the same time using JPQL:

@Test
public void whenFetchingMoreThanOneBag_thenThrowAnException() {
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> {
String jpql = "SELECT artist FROM Artist artist "
+ "JOIN FETCH artist.songs "
+ "JOIN FETCH artist.offers ";

entityManager.createQuery(jpql);
});

final String expectedMessagePart = "MultipleBagFetchException";


final String actualMessage = exception.getMessage();

assertTrue(actualMessage.contains(expectedMessagePart));
}

From the assertion, we have encountered an IllegalArgumentException,


which has a root cause of MultipleBagFetchException.

5. Domain Model
Before proceeding to possible solutions, let's look at the necessary domain
models, which we'll use as a reference later on.
Suppose we're dealing with a music app's domain. Given that, let's narrow our
focus toward certain entities: Album, Artist, and User. 
We've already seen the Artist entity, so let's proceed with the other two
entities instead.
First, let's look at the Album entity:

https://www.baeldung.com/java-hibernate-multiplebagfetchexception 4/10
10/3/2021 A Guide to MultipleBagFetchException in Hibernate | Baeldung

@Entity
class Album {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@OneToMany(mappedBy = "album")
private List<Song> songs;

@ManyToMany(mappedBy = "followingAlbums")
private Set<Follower> followers;

// constructor, equals, hashCode

An Album has a collection of songs, and at the same time, could have a set of
followers.
Next, here's the User entity:

@Entity
class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@OneToMany(mappedBy = "createdBy", cascade = CascadeType.PERSIST)


private List<Playlist> playlists;

@OneToMany(mappedBy = "user", cascade = CascadeType.PERSIST)


@OrderColumn(name = "arrangement_index")
private List<FavoriteSong> favoriteSongs;

// constructor, equals, hashCode


}

A User can create many playlists. Additionally, a User has a separate List for
favoriteSongs wherein its order is based on the arrangement index.

https://www.baeldung.com/java-hibernate-multiplebagfetchexception 5/10
10/3/2021 A Guide to MultipleBagFetchException in Hibernate | Baeldung

6. Workaround: Using a Set in a single JPQL


query
Before anything else, let's emphasize that this approach would generate a
cartesian product, which makes this a mere workaround. It's because we'll
be fetching two collections simultaneously in a single JPQL query. In
contrast, there's nothing wrong with using a Set (/java-set-operations). It is the
appropriate choice if we don't need our collection to have an order or any
duplicated elements.
To demonstrate this approach, let's reference the Album entity from our
domain model.
An Album entity has two collections: songs and followers. The collection
of songs is of type bag. However, for the followers, we're using a Set. Having
that said, we won't encounter a MultipleBagFetchException even if we try to
fetch both collections at the same time.
Using an integration test, let's try to retrieve an Album by its id while fetching
both of its collections in a single JPQL query:

@Test
public void whenFetchingOneBagAndSet_thenRetrieveSuccess() {
String jpql = "SELECT DISTINCT album FROM Album album "
+ "LEFT JOIN FETCH album.songs "
+ "LEFT JOIN FETCH album.followers "
+ "WHERE album.id = 1";

Query query = entityManager.createQuery(jpql)


.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false);

assertEquals(1, query.getResultList().size());
}

As we can see, we have successfully retrieved an Album. It's because only


the list of songs is a Bag. On the other hand, the collection of followers is a
Set.
On a side note, it's worth highlighting that we're making use
of QueryHints.HINT_PASS_DISTINCT_THROUGH. Since we're using an entity
JPQL query, it prevents the DISTINCT keyword from being included in the
actual SQL query. Thus, we'll use this query hint for the remaining approaches
as well. 
https://www.baeldung.com/java-hibernate-multiplebagfetchexception 6/10
10/3/2021 A Guide to MultipleBagFetchException in Hibernate | Baeldung

7. Workaround: Using a List in a single JPQL


query
Similar to the previous section, this would also generate a cartesian product,
which could lead to performance issues. Again, there's nothing wrong with
using a List (/java-arraylist), Set, or Bag for the data type. The purpose of this
section is to demonstrate further that Hibernate can fetch collections
simultaneously given there's no more than one of type Bag.
For this approach, let's use the User entity from our domain model.
As mentioned earlier, a User has two collections: playlists and favoriteSongs.
The playlists have no de ned order, making it a bag collection. However, for
the List of favoriteSongs, its order depends on how the User arranges it. If
we look closely at the FavoriteSong entity, the arrangementIndex property
made it possible to do so.
Again, using a single JPQL query, let's try to verify if we'll be able to retrieve all
the users while fetching both collections of playlists and favoriteSongs at the
same time.
To demonstrate, let's create an integration test:

@Test
public void whenFetchingOneBagAndOneList_thenRetrieveSuccess() {
String jpql = "SELECT DISTINCT user FROM User user "
+ "LEFT JOIN FETCH user.playlists "
+ "LEFT JOIN FETCH user.favoriteSongs ";

List<User> users = entityManager.createQuery(jpql, User.class)


.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getResultList();

assertEquals(3, users.size());
}

From the assertion, we can see that we have successfully retrieved all users.
Moreover, we didn't encounter a MultipleBagFetchException. It's because
even though we're fetching two collections at the same time, only
the playlists is a bag collection.

8. Ideal Solution: Using Multiple Queries


https://www.baeldung.com/java-hibernate-multiplebagfetchexception 7/10
10/3/2021 g p
A Guide to MultipleBagFetchException in Hibernate | Baeldung

We've seen from the previous workarounds the use of a single JPQL query for
the simultaneous retrieval of collections. Unfortunately, it generates a
cartesian product. We know that it's not ideal. So here, let's solve
the MultipleBagFetchException without having to sacri ce performance.
Suppose we're dealing with an entity that has more than one bag collection. In
our case, it is the Artist entity. It has two bag collections: songs and o ers.
Given this situation, we won't even be able to fetch both collections at the
same time using a single JPQL query. Doing so will lead to a
MultipleBagFetchException. Instead, let's split it into two JPQL queries.
With this approach, we're expecting to fetch both bag collections successfully,
one at a time.
Again, for the last time, let's quickly create an integration test for the retrieval
of all artists:

@Test
public void whenUsingMultipleQueries_thenRetrieveSuccess() {
String jpql = "SELECT DISTINCT artist FROM Artist artist "
+ "LEFT JOIN FETCH artist.songs ";

List<Artist> artists = entityManager.createQuery(jpql, Artist.class)


.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getResultList();

jpql = "SELECT DISTINCT artist FROM Artist artist "


+ "LEFT JOIN FETCH artist.offers "
+ "WHERE artist IN :artists ";

artists = entityManager.createQuery(jpql, Artist.class)


.setParameter("artists", artists)
.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getResultList();

assertEquals(2, artists.size());
}

From the test, we rst retrieved all artists while fetching its collection of songs.
Then, we created another query to fetch the artists' o ers.
Using this approach, we avoided the MultipleBagFetchException as well as
the formation of a cartesian product.

https://www.baeldung.com/java-hibernate-multiplebagfetchexception 8/10
10/3/2021 A Guide to MultipleBagFetchException in Hibernate | Baeldung

9. Conclusion
In this article, we've explored MultipleBagFetchException in detail. We
discussed the necessary vocabulary and the causes of this exception. We then
simulated it. After that, we talked about a simple music app's domain to have
di erent scenarios for each of our workarounds and ideal solution. Lastly, we
set up several integration tests to verify each of the approaches.
As always, the full source code of the article is available over on GitHub
(https://github.com/eugenp/tutorials/tree/master/persistence-
modules/java-jpa-3).

The early-bird price of the new Learn Spring Data


JPA course is increasing by $35 on Friday:
>> GET ACCESS NOW (/learn-spring-data-jpa-course#table)

Comments are closed on this article!

CATEGORIES
SPRING (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SPRING/)
REST (HTTPS://WWW.BAELDUNG.COM/CATEGORY/REST/)
JAVA (HTTPS://WWW.BAELDUNG.COM/CATEGORY/JAVA/)
SECURITY (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SECURITY-2/)
PERSISTENCE (HTTPS://WWW.BAELDUNG.COM/CATEGORY/PERSISTENCE/)
JACKSON (HTTPS://WWW.BAELDUNG.COM/CATEGORY/JSON/JACKSON/)
HTTP CLIENT-SIDE (HTTPS://WWW.BAELDUNG.COM/CATEGORY/HTTP/)

https://www.baeldung.com/java-hibernate-multiplebagfetchexception 9/10
10/3/2021 A Guide to MultipleBagFetchException in Hibernate | Baeldung

SERIES
JAVA “BACK TO BASICS” TUTORIAL (/JAVA-TUTORIAL)
JACKSON JSON TUTORIAL (/JACKSON)
HTTPCLIENT 4 TUTORIAL (/HTTPCLIENT-GUIDE)
REST WITH SPRING TUTORIAL (/REST-WITH-SPRING-SERIES)
SPRING PERSISTENCE TUTORIAL (/PERSISTENCE-WITH-SPRING-SERIES)
SECURITY WITH SPRING (/SECURITY-SPRING)

ABOUT
ABOUT BAELDUNG (/ABOUT)
THE COURSES (HTTPS://COURSES.BAELDUNG.COM)
JOBS (/TAG/ACTIVE-JOB/)
THE FULL ARCHIVE (/FULL_ARCHIVE)
WRITE FOR BAELDUNG (/CONTRIBUTION-GUIDELINES)
EDITORS (/EDITORS)
OUR PARTNERS (/PARTNERS)
ADVERTISE ON BAELDUNG (/ADVERTISE)

TERMS OF SERVICE (/TERMS-OF-SERVICE)


PRIVACY POLICY (/PRIVACY-POLICY)
COMPANY INFO (/BAELDUNG-COMPANY-INFO)
CONTACT (/CONTACT)

https://www.baeldung.com/java-hibernate-multiplebagfetchexception 10/10

You might also like