Matelutex
Matelutex

Reputation: 2220

MultipleBagFetchException - what in case when we have only one collection

There is a lot of informations about how to avoid MultipleBagFetchExeption, some answers are given eg. here: Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

I wonder if we need use multiple sql queries in case we have an Entity A with one nested collection B and that collection has collection C and collection C has collection D?

Can I use only one sql query to fetch my object with nested collections? I know that in case of A -> B,C collections I have to use 2 sql queries to avoid cartesian product but in this case A -> B -> C -> D I think one sql query without will be enough (to avoid cartesian product)?

 return entityManager.createQuery(
                "select distinct a " +
                        "from A a " +
                        "left join fetch a.B b " +
                        "left join fetch b.C c " +
                        "left join fetch c.D d " +
                        "left join fetch d.E e " +
                        "left join fetch e.F f " +
                        "where f.orderId = :orderId", A.class)
                .setParameter("orderId", orderId)
                .setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
                .getResultList()
                .stream()
                .findFirst();

where A is my entity, B,C,D,E,F are nested collections (OneToMany relations) like A has only one B collection, B has only one C collection, C has only one D collection etc.

Upvotes: 1

Views: 246

Answers (1)

Christian Beikov
Christian Beikov

Reputation: 16420

Of course you can fetch nested collections. The only problem is, if you use multiple "bags" which IMO you shouldn't at all. A bag is an unordered collection that may contain duplicates. If you choose a Set i.e. disallow duplicates, it's all fine and you can fetch join whatever you like. If you really must use a List, make sure to use ordering by using the @OrderColumn annotation so you don't get bag semantics.

Upvotes: 2

Related Questions