Five ‘s Weblog

November 9, 2007

Eager loading in Hibernate

Filed under: ORM — by powerdream5 @ 5:50 pm
Tags: , , ,

      In default, Hibernate adopts the mechanism of lazy loading to load objects from databases. Lazy loading contributes a lot to improve the performance of an application by limiting the amount of objects that will be needed. In contrast to lazy loading, eager loading loads the full objects tree once. Because eager loads multiple related objects with a single SELECT statement instead of using multiple SELECT statements, therefore in some situations, eager loads can also improve the performance of the application by reducing the times of accessing the database.

     There are two ways to configure eager loading in Hibernate. They are staticly eager loading and dynamically eager loading respectively. If the application always traverses a relationship, you might want to configure it to be always staticly eager loaded. Conversely, you might want to dynamically configure eager loading for relationships that are only traversed by the application when handling particular requests.

     One way to configure static eager loading is specifying a value for the fetch attribute of the relationship’s mapping element. 
     This attribute can have one of two values:
     select: Lazily load the referenced object or collection with a separate SQL SELECT statement. It is the default value
     join: Eagerly load the referenced object or collection using an outer join

     <class name=”?” table=”?”>
          <many-to-one name=”?” fetch=”join” column=”?” />

      To configure dynamical eager loading, you must use queries with fetch joins.
      <query name=”queryName”>
                 from student s
                 left outer join fetch s.classID as c
                 left outer join fetch c.className
                 where = ?

     Finally, take a note that Hibernate has a rule 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 too large collections.


Blog at