Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding @BatchSize in Hibernate

Tags:

java

hibernate

The Hibernate documentation gives some information at @BatchSize as :

@BatchSize specifies a "batch size" for fetching instances of this class by identifier. Not yet loaded instances are loaded batch-size at a time (default 1).

I am not clear on what is the purpose of this annotation, when we need to use this. Can some please help me in understanding when to use this annotation.

like image 452
Chaitanya Avatar asked Aug 08 '14 19:08

Chaitanya


1 Answers

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. There are two ways you can configure batch fetching: on the class level and the collection level.

Batch fetching for classes/entities is easier to understand. Consider the following example: at runtime you have 25 Cat instances loaded in a Session, and each Cat has a reference to its owner, a Person. The Person class is mapped with a proxy, lazy="true". If you now iterate through all cats and call getOwner() on each, Hibernate will, by default, execute 25 SELECT statements to retrieve the proxied owners. You can tune this behavior by specifying a batch-size in the mapping of Person:

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

Hibernate will now execute only three queries: the pattern is 10, 10, 5.

like image 192
Aun Avatar answered Oct 06 '22 13:10

Aun