Defining fetch strategy
by, 05-21-2011 at 10:33 PM (2084 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:
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.XML Code:<set name="permissions" fetch="join"> <key column="userId"/> <one-to-many class="Permission"/> </set <many-to-one name="mother" class="Cat" fetch="join"/>
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) ) .uniqueResult();