Extra lazy one-to-many mapping with Hibernate

Assume entity A has a one-to-many relationship to B. So, you’d have a method like A#getBs(). However, sometimes you might/will only need the number of Bs and not the entities themselves i.e. you need the count. However, if you called A#getBs()#getSize() you’d effectively initialize the collection and thereby loading entities into memory for no reason.

Today I learned that Hibernate has an extra-lazy mode that detects such cases. It issues the proper “select count(id) from B” SQL statement instead of “select … from B” in the background: @LazyCollection(LazyCollectionOption.EXTRA)

The enum’s JavaDoc is very terse but there’s a nice article here: http://sites.google.com/a/pintailconsultingllc.com/java/hibernate-extra-lazy-collection-fetching (also stresses the difference of list vs. bag semantics). If you happen to have a copy of “Java Persistence with Hibernate” you’d find this in chapter 13.1.3 on page 567.

One thought on “Extra lazy one-to-many mapping with Hibernate

Leave a Reply