Using batch fetching by R4R Team

Using batch fetching, Hibernate can load several uninitialized proxies if one proxy is accessed. Batch fetching is an optimization of the lazy select fetching strategy. Batch fetching for classes/entities is easier to understand. 

There are two ways you can configure batch fetching: 

1. on the class level
2. collection level.

Consider the following example: 

At runtime you have 245 Cater instances loaded in a Session, and each Cater has a reference to its owner, a Person. The Person class is mapped with a proxy, lazy="true". If you now iterate through all caters and call getOwner() on each, Hibernate will, by default, execute 245 SELECT statements to retrieve the proxied owners. Hibernate will now execute only three queries: the pattern is 10, 10, 5.You can also enable batch fetching of collections. 

You can tune this behavior by specifying a batch-size in the mapping of Person:

<class name="Person" batch-size="10">...</class>

For example: 

If each Person has a lazy collection of Caters, and 10 persons are currently loaded in the Session, iterating through all persons will generate 10 SELECTs, one for every call to getCaters(). If you enable batch fetching for the cats collection in the mapping of Person, 

Hibernate can pre-fetch collections:

<class name="Person">
    <set name="cats" batch-size="3">
        ...
    </set>
</class>

With a batch-size of 3, Hibernate will load 3, 3, 3, 1 collections in four SELECTs. Again, the value of the attribute depends on the expected number of uninitialized collections in a particular Session. Batch fetching of collections is particularly useful if you have a nested tree of items, i.e. the typical bill-of-materials pattern. However, a nested set or a materialized path might be a better option for read-mostly trees.
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!