Member-only story

The best way to fix Hibernate’s MultipleBagFetchException

Adapting from https://vladmihalcea.com plus sample codes for Spring Data JPA

Gerald Nguyen
6 min readDec 4, 2022

There are 2 articles from https://vladmihalcea.com describing his analysis and solutions to Hibernate’s MultipleBagFetchException. The first one, appeared around 2020 (when I first researched this problem) or even earlier (2018?), offered an analysis of the problem and a solution using Hibernate’s EntityManager API. The second one appeared around Jun 2022, and offers a slightly different solution for JPA.

I will present below my understanding of his analysis, his solutions, and working sample codes which you can check out and validate your understanding and/or devise your own solutions.

The sample codes are available on my GitHub. I encourage you to check it out and follow along. If you do, you may want to POST http://localhost:8080/posts/samples to set up sample data.

The entities: Post, PostComment and Tag

The entities: Post, PostComment and Tag

A Post represents a blog post with attributes such as id, title

Readers of a post may leave comments. The relationship between PostComment to Post is ManyToOne :

public class PostComment {
@Id
@GeneratedValue(strategy =…

--

--

Gerald Nguyen
Gerald Nguyen

Written by Gerald Nguyen

Engineering Lead. I write about software development, and sometimes writing itself. Mostly original. https://bit.ly/geraldnguyen

No responses yet