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:
<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.
User user = (User) session.createCriteria(User.class)
.add( Restrictions.idEq(userId) )
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.