Hibernate Facts: Multi level fetching

Vlad Mihalcea's Blog

It’s quite common to retrieve a root entity along with its children associations on multiple levels.

In our example we need to load a Forest with its Trees and Branches and Leaves, and we will try to see have Hibernate behaves for three collection types: Sets, Indexed Lists, and Bags.

This is how our class hierarchy looks like:


Using Sets and Indexed Lists is straight forward since we can load all entities by running the following JPA-QL query:

and the executed SQL query is:

But when our children associations are mapped as Bags, the same JPS-QL query throws a “org.hibernate.loader.MultipleBagFetchException”.

In case you can’t alter your mappings (replacing the Bags with Sets or Indexed Lists) you might be tempted to try the something like:

But this is inefficient generating a plethora of SQL queries:

So, my solution is to simply get the lowest level children and fetch all needed associations…

View original post 281 more words