Tuning fetch strategies With Fetching Strategies by R4R Team

In the Fetching Strategies of Hibernate When we do Select for fetching is extremely vulnerable to N+1 selects problem, so need to enable join fetching in the mapping document like as:

<set name="permissions" 
            fetch="join">
    <key column="userId"/>
    <one-to-many class="Permission"/>
</set
<many-to-one name="mother" class="Cat" fetch="join"/>

When we do fetch then the fetch strategy defined in the mapping document affects:

1. retrieval via get() or load()
2. retrieval that happens implicitly when an association is navigated
3. Criteria queries
4. HQL queries if subselect fetching is used

We defined non-lazy graph is guaranteed to be loaded into memory. This result in several immediate selects being used to execute a particular HQL query.Generally the mapping document we use for fetching but we can't use. But without using the mapping document we keep the default behavior, and override it for a particular transaction, using left join fetch in HQL. It shows Hibernate to fetch the association eagerly in the first select, using an outer join. By the using Criteria query API, use setFetchMode(FetchMode.JOIN). If want to change the fetching strategy used by get() or load(), you can use a Criteria query. 

For example:

User user = (User) session.createCriteria(User.class)
                .setFetchMode("permissions", FetchMode.JOIN)
                .add( Restrictions.idEq(userId) )
                .uniqueResult();

This is Hibernate's equivalent of what some ORM solutions call a "fetch plan".A completely different approach to problems with N+1 selects is to use the second-level cache.
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!