More Hibernate and Setters…

March 11, 2007

Over at the MD blog Darren has illustrated more dangers with Hibernate setters.


My Setter is Too Clever, Or Why Hibernate Isn’t Batching

September 23, 2006

Batch fetching is an excellent feature for improving the read performance of a Hibernate application. It is particularly useful for loading a tree of objects where each level is a child collection of the previous. In the application I’m tuning right now we have the following object model: a book has a collection of pages, and each page has a collection of content. We always load the whole graph by calling session.load(...) with the book’s id. The brute-force, non-batch database approach is to perform a SQL select to load the pages, then issue another select for each page to load the associated content. By setting a batch-size on the pages and content collections, we should greatly reduce the number of SQL selects issued to the DB.

Unfortunately, it wasn’t happening. As I tuned the app I had Hibernate’s SQL logged to the console, and I saw a content select issued for each page, despite the fact that I told Hibernate to batch fetch those objects. The reason why is that the setContent(List content) method on the page object was iterating the content right then, to initialize some state that Hibernate could not manage. The content collection was at this point an uninitialized Hibernate collection. Iterating it forced Hibernate to load it, and defeated the batch fetch processing. Moving the iteration outside of the setter, post-Hibernate, restored the proper batch fetching.

We have run into several problems by putting too much code into the getters and setters Hibernate uses to populate our objects. The closer those methods are to absolutely dumb read/write assignments, the better.