Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Hibernate hibernate.max_fetch_depth and hibernate.default_batch_fetch_size

Tags:

java

hibernate

The Hibernate documenation gives some of the Hibernate configuration properties. Among them,

hibernate.max_fetch_depth

Sets a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0 disables default outer join fetching. e.g. recommended values between 0 and 3

hibernate.default_batch_fetch_size

Sets a default size for Hibernate batch fetching of associations. e.g. recommended values 4, 8, 16

I am new to Hibernate, can someone please help me in understanding this with an example.

Thanks in advance.

like image 321
Chaitanya Avatar asked Aug 05 '14 19:08

Chaitanya


1 Answers

max_fetch_depth: Imagine a Person and an Address Entity. Each person lives at one address (very simple system), but many people might live at the same address. In the object model a Person would probably have an address property. This would be mapped as many-to-one (as the doc says). Now when fetching a Person from the database, hibernate encounters this property. In the database it's a column with a foreign key to the Address table. To fetch the associated object, a join to this table can be used. The resulting data would be used to populate an Address object that would be set on the address property on the person. In this sense Hibernate traverses the object graph when fetching an object. Now what if Address had a property City? This would also be many-to-one and would lead to a join by the same logic. What if City had a property Country? Same thing. Doing many joins would be bad for performance. At some point it would be better to do a separate select, get the data from a cache or inject a proxy. This configuration property determines how many associations hibernate will traverse by join when fetching data.

default_batch_fetch_size: This is a very low level property that determines how many rows Hibernate will request the JDBC driver to fetch/load when querying a collection association. If you would query all cities in a country (previous example) then by loading the data in batches over the JDBC connection the process of getting the data across and into memory as objects will be more streamlined. In comparison to the ring it will take for the query to execute our for the application to process the data, however, it is usually insignificant. Leaving the configuration property to default value will most often be correct.

like image 98
Maarten Winkels Avatar answered Oct 05 '22 00:10

Maarten Winkels