A Java application using Hibernate lists 200 orders with their line items. The SQL log shows one query for the orders followed by 200 separate queries, one per order, to load the items. What is the cause, and what is the usual remedy?
Select an answer to reveal the explanation.
Short Explanation
One query for the list plus one per row is the classic N+1 problem, and lazy loading is the usual culprit. It's like making 200 trips to the store for 200 items when one cart would do. Fetch the items together with a join and you're down to one trip.
Full Explanation
Object-relational mappers such as Hibernate often load associations lazily: the order objects are loaded first, and each order's line-item collection is fetched only when the code first touches it. Looping over 200 orders and reading their items therefore triggers one query for the orders plus one query per order, the N+1 pattern. Each query is cheap, but the round trips add up, and the database handles 201 statements where one or two would do. The usual remedy is to tell the ORM to load the association with the parent, for example with a fetch join in the query or a batch-fetching setting, so the items arrive in a single joined query or a few batched queries. A missing primary key would cause broader mapping problems; it does not produce one query per parent row in this pattern. Enlarging the connection pool lets more queries run concurrently but does not reduce their number, and the ORM issues them sequentially as the code iterates anyway. Eager loading enabled everywhere is the opposite condition; it tends to load too much data up front, not one query per row on access. Exam caveat: blanket eager loading can create oversized joins, so the fix should be applied to the specific query that needs the data. Operational check: enable SQL logging, rerun the listing, and confirm the log now shows one joined query instead of 201.