I have an application that contains a nested relationship between 3 classes, shown below:
Program 1:n Service 1:n SubService
Then I have to retrieve from a Program, its associated Services. This means 1 query. But then, for every Service, I want to obtain all its associated SubServices, which means n queries. (this is the typical n+1 selects problem).
The first time I access Services from a Program, Hibernate execute 1 query. But then, I load the SubService collection for every Service, which means n+1 queries, as I mentioned before.
I want to avoid this quickly by enabling batch-fetching in my mappings files. I define a ¿magic? batch-fetching number for every association.
For example, I fix:
Service 1:n SubService à batch-fetching = 10 (or any other value)
Thus, when Hibernate retrieves the first collection of SubServices for a Service, automatically it would retrieve another 9 collections if there were another 9 Services loaded (retrieved from the same Program) in this session.
I have made a few tests, and it looks as if batch-fetching is not doing this correctly ¿¿??
Suppose I have 8 Service objects loaded in the actual session, then I fix batch-fetching and I inspect the number of selects executed:
Batch-size = 2 --- 2 + 2 + 2 + 2 selects (OK)
Batch-size = 3 --- 3 + 3 + 2 selects (OK)
Batch-size = 4 --- 4 + 3 + 1 selects (surprise !!, it must be 4 + 4)
Batch-size = 5 --- 5 + 2 + 1 selects (surprise !!, it must be 5 + 3)
Etc…
I’m using Hibernate 2.1.8
¿Is batch-size not doing its job correctly? ¿Why? ¿Is something wrong ?
Thanks a lot.
|