Thursday, June 10

The Secret Hibernate Go-Faster Switch

Gavin King recently helped us with our hibernate performance and we extracted from him a few secrets, one of which is the undocumented "batch-size" attribute. To use it add the attribute as shown here:

<hibernate-mapping>
  <class name="tw.Foo" batch-size="25" />
</hibernate-mapping>

You might already know that Hibernate creates its queries on startup, but if batch-size is more than 1, it creates three. For example if batch size is 25 it create the following queries:
- select domain where id = '?'
- select domain where id = '?' or id='?' ... (for 5 possible ids)
- select domain where id = '?' or id='?' or id='?' ... (for 25 ids)

Where the size of the second query is the square root of the batch size.

If there were 10 objects in your collection hibernate will do the middle query twice rather than the default behavior that is using the first query 10 times, thus improving your performance!

When asked why this is not on by default, Gavin said he felt this feature was not the ideal way to load collections, instead he prefers some more advanced techniques, but for me, the simplicity makes it a no-brainer.