views:

187

answers:

2

Hello All

I am using Nhibernate but still i am confused about (lazy-loading and Eagerly loading) these two topics due to poor understanding of Nhibernate.

Please define me lazy-loading and Eagerly loading in simple words. Also why we use castle.Dynamic Proxy ?

+2  A: 

Lazy loading = waiting until code explicitly accesses a property/collection before loading it from the database.

Eager loading = proactively loading that data ahead of time, regardless of whether the code ever uses it or not.

Proxies are used to intercept access to said properties/collections in order to instigate the load.

HTH,
Kent

Kent Boogaart
Thanks @@Kent...
Pankaj
+5  A: 

Lazy loading and eager loading are concepts that must be present in every ORM. Let's take a parent-child relation:

class Parent {
  String name;
  List<Child> childs;
}

class Child {
  String name;
}

When you load an element of Parent, the ORM must decide if it loads the childs collection also (through a join for example) or if it delays the query to load the childs until you actually access the collection

parent.childs.get(0)
  • When you load the childs collection ahead, ie, before accessing the collection, it is eagerly loading because you are expecting to access the childs. This can be done in a single query, with the disadvantage of bringing more data from the DB.
  • When you delay the load until the actual collection is accessed, it is called lazy loading, because you are only getting the childs when they are strictly required. This has the benefit of getting only the data when its needed, at the cost of extra queries (for mor on this topic you can query google for "N+1 select hibernate" for example).

If you want to trigger the query for retrieving the childs when the collection is being accessed, you need some sort of callback/interception on the childs collection. This is done through a proxy on the collection, so you can intercept every access to the collection to get data from the db. That's why you need a proxy/interception library such as Castle.

Miguel Ping
Thanks @@Miguel.....
Pankaj
+1 Nice explanation.
ewernli