Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A query join-fetches two collections, Order.lines and Order.payments, both Lists. It fails with MultipleBagFetchException. Changing both to Set makes it run, but it becomes very slow. Explain both behaviours and the right fix.

Hibernate refuses to fetch two List collections, bags, in one query because the join produces a Cartesian product and with bags it cannot tell real duplicates from the repeated rows. With Sets the query runs, but each order still returns lines times payments rows, so an order with 20 lines and 10 payments sends 200 rows. The right fix is to fetch one collection per query, orders with lines and then the same orders with payments, and let the persistence context merge them, or to batch fetch the second collection.

Why this question is asked

This is a classic two-step trap. The first error is loud and points to a clear rule, so people search for it and find the advice to change List to Set. The error disappears, the tests pass, and weeks later the order screen takes seconds because the database is returning tens of thousands of rows. Interviewers ask about both behaviours because explaining them needs a clear picture of what a join does to collections. In this answer, we will recap what a bag is, see the rows a double fetch join produces, explain the exception and the slowness, and then write the two-query fix and the batch fetching alternative.

1A Quick Recap of Bags

In Hibernate terms, a bag is a collection that has no order column and allows duplicates. A java.util.List mapped with @OneToMany and no @OrderColumn is treated as a bag. A Set does not allow duplicates, and a List with @OrderColumn has positions; neither is a bag.

This matters for fetch joins because Hibernate builds the collections from the rows of the SQL result. With a single collection, every row is one line, and Hibernate adds each to the order's list. With two collections joined at once, the rows no longer map one to one to elements.

2The Rows a Double Fetch Join Produces

Here is the query that fails, and what the database would return for one order with three lines and two payments if Hibernate ran it.

Java
@Query("select o from Order o left join fetch o.lines left join fetch o.payments where o.status = :s")
List<Order> findWithLinesAndPayments(@Param("s") Status s);
// org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
Rows for order 7 with 3 lines and 2 payments
o.idl.skup.idp.amount
7BOOK-1P110.00
7BOOK-1P215.00
7PEN-4P110.00
7PEN-4P215.00
7MUG-2P110.00
7MUG-2P215.00
Every line appears twice and every payment three times: a Cartesian product.

Each line is combined with each payment, because the SQL joins both child tables to the order independently. Three lines times two payments gives six rows for one order.

3Why Hibernate Throws the Exception

Looking at those six rows, Hibernate has to decide how many lines the order has. BOOK-1 appears twice. Is that one line repeated by the product, or did the customer really order two separate BOOK-1 lines? A bag allows duplicates, so both answers are possible, and the rows do not say which is true. Hibernate could deduplicate and risk losing real duplicates, or keep everything and report six lines and six payments, both wrong. Rather than guess, it throws MultipleBagFetchException, usually when the query is first created.

So the exception is not a limitation of the code generator; it is Hibernate refusing to build collections it cannot build correctly.

4Why Sets Make It Run but Slowly

With Set<OrderLine> and Set<Payment>, duplicates are impossible by definition, so Hibernate can safely ignore repeated rows: it adds BOOK-1 to the set twice and the set keeps it once. The exception goes away and the collections are correct.

But the database still produces the product. For an order with 20 lines and 10 payments, the result has 200 rows. For a page of 100 such orders, it has 20,000 rows, each carrying all the order, line and payment columns, to build objects that need only 100 orders, 2,000 lines and 1,000 payments. The database does more work, the network carries far more data, and Hibernate processes every row. Add a third collection and the growth is multiplicative again. The SQL log, or the row count reported by the database, shows it immediately: the number of rows returned is much larger than the number of entities built.

Step throughHow rows grow with each collection joined
  1. 100 orders100 rows
  2. join fetch 20 lines each2,000 rows
  3. also join fetch 10 payments each20,000 rows
  4. also join fetch 3 shipments each60,000 rows

4 steps in order. Play them, or step through them one at a time.

5The Fix: One Collection per Query

We split the loading into two queries inside the same transaction. The first loads the orders with their lines. The second loads the same orders with their payments. Because both queries run in the same persistence context, the second query finds the Order objects that are already loaded and fills their payments collection, instead of creating new Order objects.

Java
@Transactional(readOnly = true)
public List<Order> loadOrdersWithDetails(Status status) {
List<Order> orders = em.createQuery("""
select o from Order o
left join fetch o.lines
where o.status = :s
""", Order.class)
.setParameter("s", status)
.getResultList(); // query 1: 100 orders, 2,000 rows
em.createQuery("""
select o from Order o
left join fetch o.payments
where o in :orders
""", Order.class)
.setParameter("orders", orders)
.getResultList(); // query 2: same orders, 1,000 rows, payments merged in
return orders; // lines and payments both initialized
}

Two queries return 3,000 rows instead of 20,000, and the collections can stay Lists. Hibernate 6 deduplicates the root entities, so the result lists contain each order once. Notice that the second result is not used directly; its effect is to initialize the payments of the orders we already hold. For very large pages, the second query can filter by the list of ids instead of by entities, which is equivalent.

6The Alternative: Batch Fetching the Second Collection

If writing a second query feels heavy, we can fetch only the lines with a join and let batch fetching load the payments. With @BatchSize(size = 50) on the payments collection, or hibernate.default_batch_fetch_size, the first access to an order's payments loads the payments for up to 50 orders in one IN query. For 100 orders that is two extra queries, close to the two-query fix, with no query code at all. The difference is that the explicit second query is predictable, while batch fetching depends on what is in the session when the first collection is touched.

Whichever we choose, a statement-count test on this use case and a look at the row counts in the SQL log confirm that the product is gone.

7Follow-up questions

Would @OrderColumn on the Lists also avoid the exception?

It removes the bag semantics, because each element now has a position, so Hibernate can tell elements apart and allows the query. But the Cartesian product is the same, so the query is just as slow as with Sets. It changes correctness, not cost.

Why does the second query not create duplicate Order objects?

Because of the persistence context, which guarantees one Java object per database row within a session. When the second query returns order 7, Hibernate finds the already-managed instance and attaches the fetched payments to it.

Is it ever fine to fetch two collections in one query?

When both collections are always very small, for example at most two or three elements each, the product is small and one query can be acceptable with Sets. It is a deliberate choice to make with measurements, not a general pattern.

8Conclusion

In this answer, we saw that two List collections in one fetch join produce a Cartesian product in which Hibernate cannot tell real duplicates from repeated rows, so it throws MultipleBagFetchException. Sets make the query legal but leave lines times payments rows per order, which is why it becomes slow. The fix is to fetch one collection per query in the same persistence context, or to batch fetch the second collection.

What to say in the interviewAbout 90 seconds aloud

Open with

Both behaviours come from the Cartesian product. If I join fetch lines and payments together, the SQL combines every line with every payment, so an order with three lines and two payments returns six rows, and each line appears twice.

Then, if they want more

Both collections are Lists without an order column, which Hibernate treats as bags that allow duplicates, so it cannot tell whether a repeated line is real or an artefact of the join. Rather than build wrong collections, it throws MultipleBagFetchException.

Switching to Sets makes duplicates impossible, so Hibernate can ignore the repeats and the query runs, but the database still returns lines times payments rows per order.

With 20 lines and 10 payments that is 200 rows per order and 20,000 for a page of 100, which is why it is slow; the SQL log shows far more rows than entities.

The right fix is one collection per query in the same transaction: first select the orders with left join fetch lines, then select the same orders with left join fetch payments. The persistence context keeps one object per row, so the second query fills the payments of the orders already loaded.

That is 3,000 rows instead of 20,000, and the Lists can stay. Alternatively I fetch the lines with a join and batch fetch the payments with @BatchSize.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A query join-fetches two collections, Order.lines and Order.payments, both Lists. It...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/2308894393/