Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on theLambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

1. Overview

In this tutorial, we’ll talk about the MultipleBagFetchException. 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 term and isn’t part of the Java Collections Framework.

Given the earlier definition, it’s worth highlighting that both List and Bag uses java.util.List. Although in Hibernate, both are treated differently. To differentiate 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.

For the first 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 offers.

Given that, let’s create the Artist entity:

@Entity
class Artist {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    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

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 offers 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).getResultList();
    });

    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:

@Entity
class Album {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    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.IDENTITY)
    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.

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. 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);

    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. 

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, 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 defined 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)
      .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

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 sacrifice 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 offers.

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)
      .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)
      .getResultList();

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

From the test, we first retrieved all artists while fetching its collection of songs.

Then, we created another query to fetch the artists’ offers.

Using this approach, we avoided the MultipleBagFetchException as well as the formation of a cartesian product.

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 different scenarios for each of our workarounds and ideal solution. Lastly, we set up several integration tests to verify each of the approaches.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments