We're updating the issue view to help you get more done. 

No MultipleBagFetchException is thrown when fetching two bags eagerly

Description

Assuming the following mapping:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 @Entity(name = "Post") @Table(name = "post") public static class Post {     @Id     private Long id;     private String title;     @OneToMany(fetch = FetchType.EAGER)     private List<PostComment> comments = new ArrayList<>();     @ManyToMany(fetch = FetchType.EAGER)     @JoinTable(name = "post_tag",         joinColumns = @JoinColumn(name = "post_id"),         inverseJoinColumns = @JoinColumn(name = "tag_id")     )     private List<Tag> tags = new ArrayList<>(); }

When fetching the Post entity directly:

1 Post post = entityManager.find(Post.class, 1L);

Hibernate generates the following SQL:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 SELECT  eagerfetch0_.id AS id1_0_0_ ,         eagerfetch0_.title AS title2_0_0_ ,         comments1_.Post_id AS Post_id1_2_1_ ,         eagerfetch2_.id AS comments2_2_1_ ,         eagerfetch2_.id AS id1_1_2_ ,         eagerfetch2_.review AS review2_1_2_ ,         tags3_.post_id AS post_id1_3_3_ ,         eagerfetch4_.id AS tag_id2_3_3_ ,         eagerfetch4_.id AS id1_4_4_ ,         eagerfetch4_.name AS name2_4_4_ FROM    post eagerfetch0_         LEFT OUTER JOIN post_post_comment comments1_ ON eagerfetch0_.id = comments1_.Post_id         LEFT OUTER JOIN post_comment eagerfetch2_ ON comments1_.comments_id = eagerfetch2_.id         LEFT OUTER JOIN post_tag tags3_ ON eagerfetch0_.id = tags3_.post_id         LEFT OUTER JOIN tag eagerfetch4_ ON tags3_.tag_id = eagerfetch4_.id WHERE   eagerfetch0_.id = 1

But if we try to execute an HQL query:

1 2 3 4 5 6 7 8 Post post = entityManager.createQuery( "select p " + "from Post p " + "join fetch p.tags " + "join fetch p.comments " + "where p.id = :id", Post.class) .setParameter("id", postId) .getSingleResult();

We get the expected exception which used to be thrown in Hibernate 4.x.

1 2 3 4 javax.persistence.PersistenceException: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags   at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)   at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1602)

Environment

None

Status

Assignee

Gail Badner

Reporter

Vlad Mihalcea

Fix versions

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Affects versions

5.1.0

Priority

Critical