Java Reference
In-Depth Information
Lazy loading occurs when the ORM framework loads objects on-demand, when
they are first accessed by the application. It is a key technique for improving per-
formance since it limits the amount of data that will be loaded. The opposite of
lazy loading is eager loading, which consists of loading multiple related objects
with a single SELECT statement instead of using multiple SELECT statements.
One way the ORM framework could allow an application to traverse relation-
ships starting from a root object would be to load all accessible objects up front.
In the case of a pending order, the framework could also load the pending
order's line items, its restaurant, and its menu items just in case the application
navigates to those objects. However, this can be inefficient because an application
typically only needs a few of what could be a large number of objects. To avoid
this overhead, the ORM framework loads objects lazily, when they are first
accessed by the application.
To understand the importance of lazy loading, consider the following. I once
ported an application from EJB 2.0 entity beans, which use lazy loading, to Hiber-
nate 2.0, which uses eager loading by default. The performance of the application
dropped from N transactions per second to 1/ N transactions per second because
of the excessive eager loading done by Hibernate. Once I configured all of the
classes to be lazily loaded, the throughput went back to N transactions per second.
Even though lazy loading is essential, eagerly loading related objects that will
be navigated to can often improve performance. For example, if the application
needs a pending order, its line items, and its restaurant, then it can load all of
those objects with a single SELECT statement. Because those objects are accessed by
the application, this approach is a lot more efficient than lazily loading one object
at a time.
The SQL statement that retrieves rows from multiple tables can use either an
inner (regular) join or an outer join. An outer join is useful because, unlike a reg-
ular join, it will return rows even if one or more of the tables contain no matching
rows. For example, a SQL statement that uses an outer join will still return the
rows from the PENDING_ORDER table even if a pending order has a null foreign
key to a restaurant or has no line items. In comparison, a regular join will not
return any rows.
The challenge, however, with using eager loading is that different requests
often access different parts of the object graph. For example, one request might
use the pending order and its restaurant, and another might use the pending
order and its line items. It can be tricky to ensure that only the required objects
are eagerly loaded by each request. In chapters 5 and 6, I explain how you can
configure JDO and Hibernate to do this.
 
 
 
 
Search WWH ::




Custom Search