Member-only story
The best way to fix Hibernate’s MultipleBagFetchException
Adapting from https://vladmihalcea.com plus sample codes for Spring Data JPA
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 TagA 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 =…