3 ms·
> WTF. No concept of the N+1 problem. Huh? I feel like I'm missing something. Eager loading, done right, is how you avoid the N+1 problem. In ActiveRecord, Cu
by JohnBooty 10y ago
> WTF. No concept of the N+1 problem.
Huh? I feel like I'm missing something. Eager loading, done right, is how you avoid the N+1 problem.
In ActiveRecord, Customer.includes(:orders).where(customer_name: 'Fred') would execute, at most, two queries even if there are many Freds with many orders.
The only real ORMs I've used are ActiveRecord and a tiny bit of EntityFramework.
Is this kind of eager loading not common? Or did I misunderstand your remark?
- snarfy 10y agoThe N+1 problem is caused by lazy loading. It's when you have an entity, e.g. Customer which has a property Orders with a foreign key relationship to Customer. The property is not materialized until it's accessed, causing an extra (N+1) query to be run. This can be avoided with something like e.g. EntityFramework which is based on the IQueryable interface and expression trees. In EF it would be var query = DbContext.Customers.Include( c => c.Orders).Where( c => c.customer_name == "Fred"); The value of query is an expression until it is iterated or converted to e.g. .ToList(); The expression is built using the relationships defined in the mapping which allows EF to use a proper SQL join, avoiding two queries and the N+1 problem.
- flukus 10y agoIf eager loading seems sub optimal then I'd guess that the have some kind of data access or repository layer on top of nhibernate. Say there are 10 places requesting customer but only 1 that needs orders, using includes would be sub optimal. Of course, it's really their architecture that's sub optimal, not hibernate.