Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

前端 未结 15 1822
广开言路
广开言路 2020-11-22 12:49

Hibernate throws this exception during SessionFactory creation:

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple b

相关标签:
15条回答
  • 2020-11-22 13:24

    To fix it simply take Set in place of List for your nested object.

    @OneToMany
    Set<Your_object> objectList;
    

    and don't forget to use fetch=FetchType.EAGER

    it will work.

    There is one more concept CollectionId in Hibernate if you want to stick with list only.

    But remind that you won't eliminate the underlaying Cartesian Product as described by Vlad Mihalcea in his answer!

    0 讨论(0)
  • 2020-11-22 13:24

    We tried Set instead of List and it is a nightmare: when you add two new objects, equals() and hashCode() fail to distinguish both of them ! Because they don't have any id.

    typical tools like Eclipse generate that kind of code from Database tables:

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }
    

    You may also read this article that explains properly how messed up JPA/Hibernate is. After reading this, I think this is the last time I use any ORM in my life.

    I've also encounter Domain Driven Design guys that basically say ORM are a terrible thing.

    0 讨论(0)
  • 2020-11-22 13:24

    Commenting both Fetch and LazyCollection sometimes helps to run project.

    @Fetch(FetchMode.JOIN)
    @LazyCollection(LazyCollectionOption.FALSE)
    
    0 讨论(0)
提交回复
热议问题