Quick revision
The short answer
No. A @OneToMany collection is all or nothing: touching it loads every order into memory, and even adding to it can trigger initialization depending on the collection type. With hundreds of thousands of orders, that means huge queries, memory spikes and slow flushes. We keep the @ManyToOne from Order to Customer, query orders through a repository with paging, and reserve mapped collections for small, bounded child sets that truly belong to the parent's aggregate.
What to remember
In this answer, we saw that a @OneToMany collection of hundreds of thousands of orders is a trap: touching it loads every order and its snapshot into memory, adding to it can trigger initialization, and serializers will try to write it all. We kept the @ManyToOne from Order to Customer, moved every orders question into repository queries with paging, counts and projections, and applied the rule that collections are mapped only for small, bounded children inside the parent's aggregate.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
No. A @OneToMany collection is all or nothing: touching it loads every order into memory, and even adding to it can trigger initialization depending on the collection type. With hundreds of thousands of orders, that means huge queries, memory spikes and slow flushes. We keep the @ManyToOne from Order to Customer, query orders through a repository with paging, and reserve mapped collections for small, bounded child sets that truly belong to the parent's aggregate.
Why this question is asked
It feels natural to model every foreign key in both directions: an order has a customer, so a customer has orders. For a customer with five orders that is harmless. For a wholesale customer with 300,000 orders, the same mapping becomes a production incident waiting for the first developer who calls customer.getOrders().size(). Interviewers ask this because the answer shows whether we think about data volumes and aggregate boundaries, not just about the shape of the schema. In this answer, we will recap how Hibernate loads collections, see exactly what goes wrong at this size, design the alternative with a repository, and finish with the rule for when a collection belongs in the model.
1A Quick Recap: How a Mapped Collection Loads
A @OneToMany collection is lazy by default, which means it is not loaded with the customer. But lazy does not mean partial. The first time any code touches the collection, by iterating it, calling size(), or passing it to a serializer, Hibernate runs one query that loads every element and builds an entity for each one in the persistence context. There is no built-in way to load the first 20 orders through the collection itself.
Each loaded entity also costs memory beyond its fields: Hibernate keeps a snapshot copy for dirty checking and entries in the persistence context's maps, and at every flush it compares each managed entity with its snapshot.
2What Goes Wrong With 300,000 Orders
Here is a harmless-looking line of code and its effect.
A rough estimate makes the cost clear: if an Order entity with its snapshot costs about 1 KB, that is around 300 MB of heap for one request, plus seconds of query and mapping time. Two such requests in parallel can push a service into long garbage collection pauses or an OutOfMemoryError.
Adding to the collection can be just as bad. With a List mapped as a bag and mappedBy, Hibernate can often queue an add without loading, but a Set has to check for duplicates, which requires the elements, and orphanRemoval, @OrderColumn or some cascade paths force initialization too. Whether a given add loads the collection depends on the type and the mapping, which is exactly the kind of hidden behaviour we do not want on a collection this large. And a JSON serializer that meets the orders field will happily try to write all 300,000.
3The Alternative: One Direction and a Repository
We keep the relationship where it is cheap and bounded, on Order, and drop the collection from Customer. Every question about a customer's orders becomes a query that says exactly how much it wants.
- Is the child set small and bounded?YesNext questionNoUse a repository query
- Does it belong to the parent's consistency rules?YesMap the collectionNoReference by id or ManyToOne
- Map with carelazy, explicit fetch plans
3 steps in order. Play them, or step through them one at a time.
Order lines pass both questions; a customer's orders fail the first.
Notice that the count is now a COUNT(*) in the database, not 300,000 entities in memory, and a page is 20 rows. For deep pages, keyset pagination (WHERE created_at < :lastSeen ORDER BY created_at DESC LIMIT 20) avoids the cost of large offsets. An index on orders (customer_id, created_at) makes all of these fast.
4Aggregate Boundaries, Not Foreign Keys
Behind this is a design idea from domain-driven design: the aggregate, a cluster of objects that must be kept consistent together and is loaded and saved as a unit. An Order with its lines is a good aggregate: there are tens of lines at most, and rules such as the total equals the sum of lines span them. A Customer and all its orders is not: no business rule needs all 300,000 orders loaded to change a customer's address, and orders are independent units with their own lifecycle.
So the rule is that collections are mapped only for small, bounded child sets that belong to the parent's aggregate. Foreign keys that cross aggregates are mapped in one direction (Order to Customer), or even just stored as an id. A foreign key in the schema does not oblige us to have a collection in Java.
5Follow-up questions
Could @BatchSize or extra-lazy collections save the mapping?
@BatchSize helps load many small collections in fewer queries, which does nothing for one huge collection. Hibernate's older extra-lazy option let size() run a count query, but it is deprecated and easy to defeat by iteration. Neither changes the fact that the collection invites code to load everything.
What if the UI needs a customer with their recent orders?
Make it two queries in the service: load the customer, then the first page of orders as DTOs, and combine them into a response object. That is explicit, bounded, and easy to cache.
Is a filtered collection mapping, such as @SQLRestriction on recent orders, a good compromise?
Rarely. The filter is fixed at mapping time and still loads every matching row, and it gives the collection a misleading meaning. A repository method with parameters is clearer and safer.
6Conclusion
In this answer, we saw that a @OneToMany collection of hundreds of thousands of orders is a trap: touching it loads every order and its snapshot into memory, adding to it can trigger initialization, and serializers will try to write it all. We kept the @ManyToOne from Order to Customer, moved every orders question into repository queries with paging, counts and projections, and applied the rule that collections are mapped only for small, bounded children inside the parent's aggregate.
Open with
I wouldn't map that collection. A @OneToMany is lazy, but it isn't partial: the first time anything touches it, size, iteration, or a JSON serializer, Hibernate loads every order for that customer into the persistence context, along with a snapshot of each for dirty checking.
Then, if they want more
At 300,000 orders that's hundreds of megabytes and seconds of work for one request, and every flush has to check all of them. Even adding an order through the collection can initialise it depending on the collection type and mapping, for example a Set has to check for duplicates.
So I'd keep the @ManyToOne from Order to Customer, which is cheap and bounded, and answer every question about a customer's orders with a repository query: a paged query sorted by date, a count query, or a DTO projection for recent orders, with an index on customer_id and created_at, and keyset pagination for deep pages.
The general rule I use is that collections in the model are only for small, bounded child sets that belong to the parent's aggregate, like order lines, where the parent's consistency rules actually span the children. A customer's orders have their own lifecycle, so aggregate boundaries should follow consistency needs, not every foreign key in the schema.
About this answer
- Last updated
- 12 November 2026
- 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.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 Customer has hundreds of thousands of Orders. Should Customer have a @OneToMany...": https://scrivio-interview-library.netlify.app/databases/jpa-relationships/862c6c3452/