Java Reference
In-Depth Information
This, of course, requires changes to the domain model, which runs counter to the
idea of transparent persistence.
Using lazy property loading
The other way to lazily load related objects is to use Hibernate's lazy property
fetching mechanism, which was introduced in Hibernate 3. This mechanism lets
you specify that a property should be loaded only when it is first accessed instead
of when the object is loaded. Its primarily purpose is to improve performance by
loading large fields only when absolutely necessary. It uses a bytecode enhancer to
instrument the Java class files. You can use lazy property fetching to lazily load
related objects without using proxies and thereby solve the problem with
instan-
ceof
and downcasting. However, as you will see later it has some important draw-
backs and using lazy property fetching is rarely worthwhile.
To lazily load a related class, you must configure the
<many-to-one>
or
<one-
to-one>
association element that references the class to use lazy loading. You
must also disable proxying for the referenced class. For example, you can lazily
load a
PendingOrder
's coupon by configuring the
PendingOrder
's
coupon
property
with
lazy="true"
. Here is an excerpt from the
O/R
mapping document for the
PendingOrder
and
Coupon
classes that does this:
<class name="PendingOrder" table="PENDING_ORDER">
…
<many-to-one name="coupon"
class="AbstractCouponImpl"
column="COUPON_ID"
lazy="true"
fetch="select"
/>
…
</class>
<class name="AbstractCouponImpl"
lazy="false"
table="COUPON">
…
The
lazy="true"
attribute of the
<many-to-one>
element specifies that the
coupon
property should only be loaded when it is first accessed. The
fetch="select"
pre-
vents Hibernate from eagerly loading the
Coupon
using an outer join. The
lazy="false"
attribute of the
<class>
element for the
AbstractCouponImpl
class
tells Hibernate to not use a proxy for this class.
When Hibernate loads a
PendingOrder
, it will neither load the
Coupon
nor cre-
ate a proxy for it. A
Coupon
will only be loaded when the application accesses the
Search WWH ::
Custom Search