Comparison
Eager loadingvsLazy loading
Eager loading
you told the query to bring the customers along with the orders, and the hundred and one queries became one.
Fetching associated data in the same query as the parent, by join or by a second batched query. It is the fix for N+1 and the cause of the opposite problem: joining several collections at once multiplies rows and can fetch far more data than the page needed. Choosing between them per use case, rather than globally, is the actual answer.
Full entry →Lazy loading
you looped over a hundred orders reading customer.name, and the log showed a hundred and one queries.
Deferring the loading of an associated object until it is first accessed, usually through a virtual proxy or a marker on the field. It makes a naive read cheap and makes the cost of a loop invisible, which is the entire mechanism behind the N+1 query problem. It also produces the other classic failure — touching a lazy field after the session has closed, which fails at a point far from the query that caused it.
Full entry →