Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a Spring Data repository method that loads an Order with its lines and customer in one query, using @Query and using @EntityGraph.

With @Query we write select o from Order o join fetch o.lines join fetch o.customer where o.id = :id and return Optional<Order>; with @EntityGraph(attributePaths = {"lines", "customer"}) on a findById declared in the repository, Spring Data generates the joins for the inherited method. A collection fetch join multiplies rows, which Hibernate 6 deduplicates for root entities automatically, and fetching two List collections at once fails with MultipleBagFetchException.

Why this question is asked

Loading an aggregate with its parts in one query is something almost every service does: an order detail page needs the order, its lines and its customer. Done naively, it runs three or more queries, and inside a list it becomes N+1. Interviewers ask for this repository method to check that we can write a fetch join correctly, know the entity graph alternative, and understand two well-known pitfalls. In this answer, we will recap the entities, write the @Query version, write the @EntityGraph version, look at the rows the database returns, and then cover the MultipleBagFetchException trap.

1The Entities We Are Loading

Order has a lazy @ManyToOne to Customer and a lazy @OneToMany list of OrderLine. Lazy means the associated data is not loaded with the order; Hibernate places a proxy or a collection wrapper in the field and loads it on first access. Without a fetch plan, an order detail page runs one query for the order, one for the customer and one for the lines.

Java
@Entity @Table(name = "orders")
public class Order {
@Id @GeneratedValue private Long id;
@ManyToOne(fetch = FetchType.LAZY) private Customer customer;
@OneToMany(mappedBy = "order") private List<OrderLine> lines = new ArrayList<>();
}
Order o = orderRepository.findById(7L).orElseThrow(); // select ... from orders where id = 7
o.getCustomer().getName(); // select ... from customer where id = ?
o.getLines().size(); // select ... from order_line where order_id = 7

Three queries for one page. In a detail view that is tolerable, but the same pattern in a loop is how N+1 starts, and outside a transaction the last two lines would throw LazyInitializationException.

2Version 1: A Fetch Join With @Query

A fetch join tells Hibernate to load the association in the same SQL statement and fill the fields with real objects.

Java
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("""
select o from Order o
left join fetch o.lines
join fetch o.customer
where o.id = :id
""")
Optional<Order> findWithDetails(@Param("id") Long id);
}
Optional<Order> o = orderRepository.findWithDetails(7L);
// select o.*, l.*, c.* from orders o
// left join order_line l on l.order_id = o.id
// join customer c on c.id = o.customer_id
// where o.id = ? -- 1 query
o.get().getLines().size(); // 3, no query

Notice the left join on lines. A plain join fetch o.lines is an inner join, so an order with no lines would not be found at all, and findWithDetails would return an empty Optional for an order that exists. The customer is required, so an inner join is fine there. The method name is our choice; giving it a name of its own makes it clear at the call site that this method loads details.

3Version 2: An Entity Graph on findById

An entity graph lists the attributes to load and lets Spring Data and Hibernate generate the joins. If we redeclare findById in our repository with @EntityGraph, the inherited method uses that graph.

Java
public interface OrderRepository extends JpaRepository<Order, Long> {
@Override
@EntityGraph(attributePaths = {"lines", "customer"})
Optional<Order> findById(Long id);
}
orderRepository.findById(7L);
// select ... from orders o left join order_line l ... left join customer c ... where o.id = ? -- 1 query

This needs no JPQL, and Hibernate uses left joins for graph attributes, so orders without lines are still found. The trade-off is scope: every caller of findById now loads lines and customer, including code that only wanted the order's status. When different callers need different data, a separate method such as @EntityGraph(attributePaths = {"lines", "customer"}) Optional<Order> findDetailedById(Long id) keeps the default findById light.

4What the Database Returns

Joining a collection produces one row per line, with the order and customer columns repeated on each row. For an order with three lines, the result has three rows.

Rows returned for order 7 with three lines
o.idc.namel.skul.qty
7Asha RaoBOOK-11
7Asha RaoPEN-42
7Asha RaoMUG-21
The order and customer columns repeat on every line row.

Hibernate builds one Order from these rows and puts three lines in its collection. For a single order by id this is harmless. For a query returning many orders, older Hibernate versions returned the same Order object once per row, which is why queries used select distinct o. Hibernate 6 deduplicates root entities of fetch join queries automatically, so the result list contains each order once without distinct. The rows themselves still travel over the network, so a fetch join of a large collection for many orders can move a lot of repeated data.

5The MultipleBagFetchException Trap

Suppose Order also has List<Payment> payments and we try to fetch both lists in one query.

Java
@Query("select o from Order o left join fetch o.lines left join fetch o.payments where o.id = :id")
Optional<Order> findEverything(@Param("id") Long id);
// fails at startup or first use:
// org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

A List without an order column is a bag in Hibernate's terms, a collection that may hold duplicates and has no position. Joining two collections produces a Cartesian product, lines times payments rows, and with two bags Hibernate cannot tell which repeated rows are real duplicates and which come from the product, so it refuses. Changing the lists to Sets makes the error go away but keeps the product, which can be very slow. The right approach is to fetch one collection per query: load the order with its lines, then run a second query that fetches payments for the same order, and the persistence context merges both into the same Order object.

6Follow-up questions

Can I use pagination with a collection fetch join?

Not safely in SQL. Limiting rows would cut an order's lines in half, so Hibernate applies the limit in memory and logs a warning, which loads everything first. For lists, page the order ids in one query, then fetch the details for those ids in a second query, or use batch fetching for the lines.

Is an entity graph better than a fetch join?

Neither is better in general. An entity graph is declarative and fits derived and inherited methods well; a fetch join gives full control over join types and conditions. Both produce similar SQL. Teams usually use entity graphs for simple cases and @Query for anything with conditions.

Why use a text block in @Query?

Java text blocks, available since Java 15, keep multi-line JPQL readable and avoid string concatenation. The annotation value is still a compile-time constant, so it works exactly like a one-line string.

7Conclusion

In this answer, we loaded an Order with its lines and customer in one query, first with a @Query fetch join, using a left join for the optional lines, and then with @EntityGraph on a redeclared findById. We saw that a collection fetch join repeats the order on every line row, which Hibernate 6 deduplicates automatically, and that two List collections cannot be fetched together, so the second collection is loaded in a separate query.

What to say in the interviewAbout 80 seconds aloud

Open with

With @Query I would write: select o from Order o left join fetch o.lines join fetch o.customer where o.id = :id, returning Optional<Order> from a method like findWithDetails with @Param("id") Long id.

Then, if they want more

I use a left join for lines, because an inner join would make an order without lines disappear, and an inner join for the required customer. That gives one SQL statement and real objects instead of proxies.

With an entity graph, I would redeclare findById in the repository with @EntityGraph(attributePaths = {"lines", "customer"}), and Spring Data applies the graph to the inherited method, so Hibernate generates left joins. The catch is that every caller of findById then loads lines and customer, so I often prefer a separate method name for the detailed version. Two pitfalls.

First, a collection fetch join returns one row per line, with the order repeated; Hibernate 6 deduplicates root entities automatically, so distinct is no longer needed, but the repeated data still travels and collection fetch joins cannot be paginated in SQL.

Second, fetching two List collections, such as lines and payments, fails with MultipleBagFetchException because Hibernate cannot untangle duplicates in the Cartesian product of two bags. I would fetch the second collection in a separate query in the same transaction rather than switching to Sets.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6, Java 15
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 "Write a Spring Data repository method that loads an Order with its lines and customer in...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/408ff3f35f/