Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

前端 未结 15 1823
广开言路
广开言路 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:05

    I think a newer version of hibernate (supporting JPA 2.0) should handle this. But otherwise you can work it around by annotating the collection fields with:

    @LazyCollection(LazyCollectionOption.FALSE)
    

    Remember to remove the fetchType attribute from the @*ToMany annotation.

    But note that in most cases a Set<Child> is more appropriate than List<Child>, so unless you really need a List - go for Set

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

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

    you can keep booth EAGER lists in JPA and add to at least one of them the JPA annotation @OrderColumn (with obviously the name of a field to be ordered). No need of specific hibernate annotations. But keep in mind it could create empty elements in the list if the chosen field does not have values starting from 0

     [...]
     @OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
     @OrderColumn(name="orderIndex")
     private List<Child> children;
     [...]
    

    in Children then you should add the orderIndex field

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

    At my end, this happened when I had multiple collections with FetchType.EAGER, like this:

    @ManyToMany(fetch = FetchType.EAGER, targetEntity = className.class)
    @JoinColumn(name = "myClass_id")
    @JsonView(SerializationView.Summary.class)
    private Collection<Model> ModelObjects;
    

    Additionally, the collections were joining on the same column.

    To solve this issue, I changed one of the collections to FetchType.LAZY since it was okay for my use-case.

    Goodluck! ~J

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

    For me, the problem was having nested EAGER fetches.

    One solution is to set the nested fields to LAZY and use Hibernate.initialize() to load the nested field(s):

    x = session.get(ClassName.class, id);
    Hibernate.initialize(x.getNestedField());
    
    0 讨论(0)
  • 2020-11-22 13:14

    Simply change from List type to Set type.

    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:17

    I found a good Blog post about the behaviour of Hibernate in this kind of object mappings: http://blog.eyallupu.com/2010/06/hibernate-exception-simultaneously.html

    0 讨论(0)
提交回复
热议问题