Wednesday, July 23, 2008

Hibernate Bug when counting Extra Lazy Collections mapped with @Where

For a quick background, the @Where annotation can be put on a Collection to specify additional SQL conditions. The @LazyCollection annotation can be used to specify when and how to load a collection. For example, using LazyCollectionOption.EXTRA tells hibernate to prefer extra queries to overfilling eagerly. This means go beyond Hibernate's normal lazy loading and is useful when dealing with very large collections, since it will cause hibernate to execute COUNT statements when accessing the size of an unloaded collection, rather than load the whole collection normally. If you know that you frequently query the size of a large collection without needing any of the actual elements, this boosts performance.

However, today I had an odd situation. I have a collection that was mapped with both a @Where annotation and @LazyCollection(LazyCollectionOption.EXTRA). When querying the size of my collection, I was getting a result of 2, yet when I attempted to iterate the collection, the size was returning 0. Excuse me? How is that?

Well, after enabling SQL logging and taking a look at what was going on, I discovered that when executing a COUNT query as specified by @LazyCollection(LazyCollectionOption.EXTRA), Hibernate ignored the @Where annotation. When loading the elements of the collection, however, Hibernate correctly minded the @Where annotation. Since the @Where condition I was specifying was actually significant, these two methods returned different results.

Clearly, this isn't ideal behavior. But, since it exists, I imagine that it doesn't come up often. Also, for those paying close attention and asking why I have LazyCollectionOption.EXTRA on any collection that has 2 items, the answer is because it's in early development right now and will not have only 2 items in practice.

Off to file a Hibernate bug report....

1 comments:

Lutz said...

I think this http://opensource.atlassian.com/projects/hibernate/browse/HHH-3319
is the bug you are looking for.