256
Logo

Multiple Eager Collections in a Hibernate Object

So I just learned something about Hibernate objects that I though I'd pass along. Hibernate has two common types of fetching modes for fields in an object: eager and lazy. Eager fetching means that when you get the object, the field is also loaded. Lazy loading means that the field is initialized with a proxy object and when you access it later, it will be loaded with a second query. Lazy loading is fine however it means that you have to have valid SessionWrappers in place which we've found to be problematic in some circumstances.

Eager fetching works fine in most cases until you try to have multiple eager fetched collections in an object. As an example, you might have a customer object which has a list of orders and a list of forum posts. If these collections are both set to be eager fetched you will probably get something like the following:

org.hibernate.HibernateException: cannot simultaneously fetch multiple bags
at org.hibernate.loader.BasicLoader.postInstantiate(BasicLoader.java:66)

Multiple "bags" meaning multiple collections. Because Hibernate is using joins to load all of the data in a single query, it cannot do more than one outer join to initialize both collections. We just discovered that you can use the FetchMode.SUBSELECT annotation in front of each collection to tell Hibernate to go ahead and perform extra queries necessary to initialize all of the eager collections:

@CollectionOfElements(fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SELECT)
private List<Image> images;

This seems to work well and no longer causes us to have to lazy load these collections. We also tried the following which worked as well but user comments on other pages said that it was slower than SELECT.

@Fetch(value = FetchMode.SUBSELECT)

Here's a discussion of the issue with more solutions and user comments.

I consider myself to be far from a Hibernate guru so please send me mail to correct any problems with the above documentation or to share your own bits of wisdom that I can add to this page. Enjoy.

Free Spam Protection   Android ORM   Simple Java Magic   JMX using HTTP   Great Eggnog Recipe   Massachusetts Covid Vaccine Sites