Java Reference
In-Depth Information
The
fetch
attribute does not affect the behavior of
HQL
queries.
HQL
queries that
need to eagerly load objects must use fetch joins, which are described next.
Second, for one-to-many and many-to-many relationships the
fetch
attribute
works in conjunction with the
lazy
attribute to determine how and when the
related objects are loaded. The collection mapping elements such as
<list>
and
<map>
also have a
lazy
attribute, which determines how the collection is loaded if
fetch="select"
. If
lazy="true"
then the collection is loaded when it is accessed
by the application, but if
lazy="false"
then Hibernate loads the collection imme-
diately using a separate
SQL
SELECT
statement. Table 6.2 summarizes this behavior.
Table 6.2
How the fetch and lazy attributes control the loading of collection
fetch=select (default)
fetch=join
lazy=true (default)
Load collection when accessed
by application
Eagerly load collection using
an outer join
lazy=false
Eagerly load collection using a
separate
SELECT
statement
Eagerly load collection using
an outer join
One limitation of Hibernate is that a class can only have at most one collection
loaded using an outer join. This is to prevent inefficient queries that return the
Cartesian product of two large collections. However, this does mean that if you
want to load multiple collections then you have to write the extra code to load
them rather than relying on Hibernate to do it for you.
Dynamically configuring eager loading using fetch joins
Sometimes statically configuring eager loading in the
O/R
mapping works quite
well. If a relationship is always traversed, then it can be configured to use eager
loading in its
mapping
element. However, different requests often require differ-
ent objects to be eagerly loaded. For example, in chapter 4 we saw how the
update
quantities
request requires the pending order, its restaurant, and its restaurant
menu items to be loaded whereas the
update payment information
request requires
the pending order, its restaurant, its line items, and their menu items to be
loaded. To accomplish this, you must dynamically control eager loading by using
queries with fetch joins.
A fetch join is a query construct that identifies a relationship to eagerly load.
When the application executes a query containing one or more fetch joins, Hiber-
nate executes a
SQL
SELECT
that retrieves the related objects using joins. One
thing to remember is that
HQL
queries ignore the
fetch
join
attribute specified
Search WWH ::
Custom Search