View RSS Feed

My Java Tips

Defining fetch strategy

Rate this Entry
by , 05-21-2011 at 11:33 PM (2189 Views)
To tune fetch strategy, you have various options. Which to choose depends on the scenario. You may define the fetch strategy in the mapping document. For instance:

XML Code:
<set name="permissions" 
    <key column="userId"/>
    <one-to-many class="Permission"/>
<many-to-one name="mother" class="Cat" fetch="join"/>
This will work but usually mapping document in not a nice place to define the fetch strategy. You may define the fetch strategy in HQL queries or in Criteria queries. This actually overrides the default behavior defined in the mapping document.

If you wish to define fetch strategy in HQL, use left join fetch in HQL. This tells Hibernate to fetch the association eagerly in the first select, using an outer join. In the Criteria query API, you would use setFetchMode(FetchMode.JOIN).

Java Code:
User user = (User) session.createCriteria(User.class)
                .setFetchMode("permissions", FetchMode.JOIN)
                .add( Restrictions.idEq(userId) )

Submit "Defining fetch strategy" to Facebook Submit "Defining fetch strategy" to Digg Submit "Defining fetch strategy" to Submit "Defining fetch strategy" to StumbleUpon Submit "Defining fetch strategy" to Google

Tags: hql Add / Edit Tags