4.4.4.3. Lazy Loading

Loading on demand (lazy loading) allows delayed loading of linked entities, i.e. they get loaded when their properties are accessed for the first time.

Lazy loading generates more DB queries than eager fetching, but it is stretched in time.

  • For example, in case of lazy loading of a list of N instances of entity A, each containing a link to an instance of entity B, will require N+1 requests to DB.

  • It is important to aim towards fewer requests to DB to minimize response time and load levels. The platform uses the mechanism of views to achieve this. Using view allows ORM to create only one request to DB with table joining for the above mentioned case.

  • If A includes a collection of B, then eager fetching will result in an SQL request, returning Cartesian product of rows A and B.

  • Sometimes lazy loading provides better performance than eager fetching. For example, when an asynchronous process is carrying out business logic, the execution time may not be critical and it may be better to distribute the load on DB in time.

Lazy loading works only for instances in Managed state, i.e. within the transaction which loaded the specified instance.