Handling MultipleBagFetchException in Hibernate while using FetchType.EAGER

Syed Hasan
2 min readSep 26, 2021
Troubleshooting MultipleBagFetchException

I thought to write this article a long time ago but I couldn’t manage time. This might be one of the most struggling part for most of the self learners and difficult to find a straightforward correct answer over the internet for them (at least it was so for me!). While using an ORM we often use @ManyToMany or @OneToMany or @OneToOne annotations. To fetch their data while fetching the parent object, the easiest way to do is FetchType.EAGER. But then it creates a hell with the mighty MultipleBagFetchException.

MultipleBagFetchException

The main reason of this problem is not only because we have used FetchType.EAGER, but we have used List for the mapped attributes. We should use Set instead of Map in case we are certain to have unique elements for our mapping.

So our old entity design was like below (Using List for attachments and locations):

And new design of our entity after Replacing List with Set, it will look like below:

And our application will not fail to create SessionFactory.

But note that, using FetchType.EAGER is a very very bad approach. Hench, we will be using FetchType.LAZY while making designing our entities. A mindful walkthrough to do the Lazy fetching and solving it’s related problem will be found in my another article, here is the link.

--

--

Syed Hasan

Software Engineer | Back-End Developer | Spring Developer | Cloud Enthusiast