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:

Image

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s