2

I've been too much time trying to do something that seems simple at first look:

Let's say I have a Store entity with two @OneToMany relationships:

@Entity
public class Store {

    private String name;

    @OneToMany(mappedBy = "store")
    private List<Foo> foos;

    @OneToMany(mappedBy = "store")
    private List<Bar> bars;

}

I want to fetch both lists with the same query. I want to use Entity Graphs, because I need to decide in execution time which children I want to fetch.

@EntityGraph(attributePaths = {"foos", "bars"})
Store findByName(String name);

This causes:

MultipleBagFetchException: cannot simultaneously fetch multiple bags.

I don't want to use Set instead of List, because the purpose of this approach is to avoid the N+1 query problem and the Cartesian product problem (the entity hierarchy is much bigger than the example), so no lazy fetching or changing List into Set do help in this case.

Also, the first answer proposed here does not work with Entity Graphs.

Any ideas?

Carlos López Marí
  • 1,183
  • 2
  • 13
  • 41
  • `I need to decide in execution time which children I want to fetch` You will still be having different method per each unique combination of elements in `attributePaths` right? – JavaLearner Jan 17 '21 at 07:13
  • 1
    Does this answer your question? [Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags](https://stackoverflow.com/questions/4334970/hibernate-throws-multiplebagfetchexception-cannot-simultaneously-fetch-multipl) – silentsudo Jan 17 '21 at 07:48
  • @JavaLearner Yes, one different query per use-case – Carlos López Marí Jan 17 '21 at 10:52
  • @silentsudo No. That doesn't apply to Entity Graphs. – Carlos López Marí Jan 17 '21 at 10:52
  • Have you explored the option of fetching directly from `Foo` and `Bar` based on FK id to store? – JavaLearner Jan 17 '21 at 16:37

0 Answers0