Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

Loading 100 Order entities runs 101 extra queries, one per order for its Invoice, although Invoice is mapped @OneToOne(mappedBy = "order", fetch = FetchType.LAZY) on Order. Explain why, and give three fixes with their trade-offs.

Order is the inverse side of the one-to-one, so its row has no invoice column, and Hibernate cannot know whether an invoice exists without querying. To choose between null and a proxy it loads each order's invoice, which gives one extra select per order. The fixes are to make the relation unidirectional from Invoice and query invoices by order id, to join fetch the invoice in queries that need it, or to use bytecode enhancement so the field is truly lazy; batch fetching and a shared primary key help reduce the cost.

Why this question is asked

This bug looks like a contradiction: the mapping says LAZY, yet loading a page of orders runs a query per order. It is one of the most common performance surprises in Hibernate, and it often goes unnoticed until a list page with 100 rows takes a second to render. Interviewers ask it because the explanation shows whether we understand what a lazy proxy is and what the database row can and cannot tell Hibernate. In this answer, we will reproduce the queries, see why the inverse side cannot be lazy, and go through three fixes with their trade-offs, plus two ways to soften the cost.

1Reproducing the 101 Queries

Invoice owns the relationship: its table has an order_id foreign key. Order maps the other side with mappedBy.

Java
@Entity @Table(name = "orders")
class Order {
@Id @GeneratedValue Long id;
@OneToOne(mappedBy = "order", fetch = FetchType.LAZY)
Invoice invoice;
}
@Entity
class Invoice {
@Id @GeneratedValue Long id;
@OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "order_id", unique = true)
Order order;
}
List<Order> orders = em.createQuery("select o from Order o where o.status = 'OPEN'", Order.class)
.setMaxResults(100).getResultList();
// select ... from orders where status = 'OPEN' fetch first 100 rows only -- 1
// select ... from invoice where order_id = ? -- 100 times

We never called getInvoice(). The extra queries happen while the orders are being loaded, which is the sign that Hibernate is resolving the association eagerly.

2Why the Inverse Side Cannot Be a Proxy

A lazy association normally works by putting a proxy, a placeholder object that loads the real entity on first use, into the field. But the field may also need to be null, when the order has no invoice yet. Look at what Hibernate has when it reads a row of orders: an id, a status, a total. Nothing in that row says whether an invoice exists, because the foreign key lives in the invoice table.

If Hibernate put a proxy there and the invoice did not exist, code checking order.getInvoice() != null would get a wrong answer, and touching the proxy would fail. So Hibernate has to find out, and the only way is a query on invoice by order_id. Since it is running that query anyway, it loads the invoice. The owning side has no such problem: Invoice's row holds order_id, so a null means no order and a value lets Hibernate build a proxy at no cost.

Step throughLoading 100 orders with an inverse one-to-one
ServiceHibernateDatabase
query open orders
select from orders (100 rows)
100 rows, no invoice column
select invoice where order_id = 1
select invoice where order_id = 2
... 98 more
100 orders with invoices set

7 messages in order. Play them, or step through them one at a time.

The extra selects exist to decide null or not null for each order.

3Fix 1: Map the Relation Only From Invoice

Remove the invoice field from Order. Invoice keeps its @ManyToOne-like lazy reference to Order, and code that needs an invoice asks for it explicitly.

Java
interface InvoiceRepository extends JpaRepository<Invoice, Long> {
Optional<Invoice> findByOrderId(Long orderId);
List<Invoice> findByOrderIdIn(Collection<Long> orderIds); // one query for a whole page
}
List<Order> orders = orderRepository.findOpen(PageRequest.of(0, 100)); // 1 query
Map<Long, Invoice> invoices = invoiceRepository
.findByOrderIdIn(orders.stream().map(Order::getId).toList())
.stream().collect(Collectors.toMap(i -> i.getOrder().getId(), i -> i)); // 1 query

This gives us complete control: list pages run two queries, and screens that never show invoices run one. The cost is convenience. There is no order.getInvoice() navigation, and code that used it must change, which in a large codebase is real work.

4Fix 2: Fetch Join the Invoice When It Is Needed

If most screens that load orders also show their invoices, we can load both in one query with a left join fetch, or with an entity graph on the repository method.

Java
@Query("select o from Order o left join fetch o.invoice where o.status = :status")
List<Order> findOpenWithInvoice(@Param("status") String status);
// select o.*, i.* from orders o left join invoice i on i.order_id = o.id where o.status = ? -- 1 query
@EntityGraph(attributePaths = "invoice")
List<Order> findByStatus(String status); // same effect

It must be a left join, otherwise orders without an invoice disappear from the result. The trade-off is that it only fixes the queries we change. Every other query that loads orders without the fetch still runs the per-order selects, so this fix is local, not structural.

5Fix 3: Bytecode Enhancement for True Laziness

Hibernate's bytecode enhancement, enabled with the Hibernate Gradle or Maven plugin and its lazy initialization option, rewrites entity classes at build time so that field access goes through Hibernate. The invoice field can then stay unloaded with no proxy at all; Hibernate runs the query only when getInvoice() is actually called, and returns null or the invoice then.

It solves the problem for the mapping as written, which is attractive in a large codebase. The cost is build complexity, a plugin that must match the Hibernate version, behaviour changes for every enhanced entity, and debugging that is harder because the classes at runtime are not exactly the ones we wrote. Teams should adopt it deliberately, not as a patch for one association.

6Softening the Cost: Shared Keys and Batch Fetching

Two further measures reduce the damage without removing it. Sharing the primary key with @MapsId, so the invoice's id is the order's id, turns each lookup into a primary key lookup and removes a separate unique index. And setting hibernate.default_batch_fetch_size, for example to 50, can let Hibernate load uninitialized associations for several owners with an IN list instead of one query each. How far batching applies to the inverse side of a one-to-one depends on the Hibernate version and the query, so check the SQL log rather than assuming it turns 100 queries into 2.

Whatever we choose, the habit that finds these issues is the same: look at the SQL log or a statement count for each list screen, because the Java code alone does not reveal them.

7Follow-up questions

Which fix would you choose in a large existing codebase?

I would start with Fix 2 on the hot list screens, because it is a small, safe change that removes the worst N+1 quickly. Then I would plan Fix 1 as the structural change, removing the inverse field and migrating callers over a few releases. I would choose bytecode enhancement only if the team is ready to adopt it for all entities.

Does the same problem happen with em.find(Order.class, id)?

For a single entity, Hibernate often resolves the inverse one-to-one with a join in the same statement, so it looks fine. The per-row queries appear with JPQL and Criteria queries that return many orders. That difference is why the problem tends to show up first on list pages.

How do I make sure the N+1 does not come back?

Write a test around the list use case that counts statements, with Hibernate statistics or datasource-proxy, and asserts the expected number, for example 2 for orders plus invoices. If someone adds back the inverse mapping or removes the fetch join, the test fails.

8Conclusion

In this answer, we saw that the inverse side of a one-to-one cannot be a lazy proxy because the order row does not tell Hibernate whether an invoice exists, so Hibernate queries each one and creates N+1. The fixes are to map the relation only from Invoice and query invoices explicitly, to join fetch the invoice where it is needed, or to use bytecode enhancement, and shared primary keys and batch fetching can reduce the remaining cost.

What to say in the interviewAbout 80 seconds aloud

Open with

The orders query runs once, and then Hibernate runs one select on invoice per order because Order is the inverse, mappedBy side of the one-to-one. A lazy association is implemented with a proxy, but the field must be null when there is no invoice, and the orders row has no column saying whether one exists; the foreign key is in the invoice table.

Then, if they want more

So Hibernate cannot choose between null and a proxy without querying, and once it queries, it loads the invoice. That is the N+1, and the LAZY hint cannot change it. I would offer three fixes.

One, map the relation only from Invoice, which owns the foreign key, and load invoices explicitly, for example findByOrderIdIn for a whole page; that is fully controlled but removes order.getInvoice navigation. Two, left join fetch the invoice or use an entity graph in queries that need it, which is quick but only fixes the queries we change.

Three, bytecode enhancement with lazy initialization, which makes the field truly lazy everywhere but adds a build plugin and changes all entities. I would also share the primary key with @MapsId so lookups are by id, check whether default_batch_fetch_size reduces the queries in our version, and add a statement count test for the list screen.

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.
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 "Loading 100 Order entities runs 101 extra queries, one per order for its Invoice...": https://scrivio-interview-library.netlify.app/databases/jpa-relationships/229df91ed4/