1

I'm writing a criteria api request to resolve some N+1 issues. My entities looks something like this:

AEntity
  ...
  List<BEntity>
BEntity
  ...
  List<CEntity>
CEntity
  ...
  List<DEntity>
DEntity
  ...

When i run the query hibernate blows up and gives me this error message:

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags: [org.company.crs.model.AEntity.bEntityList, org.company.crs.model.BEntity.cEntityList, org.company.crs.model.CEntity.dEntityList]

All that from this innocent looking code:

        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<AEntity> query = criteriaBuilder.createQuery(AEntity.class);
        Root<AEntity> conference = query.from(AEntity.class);

        Fetch<AEntity, BEntity> pages = conference.fetch(AEntity_.bEntityList, JoinType.LEFT);
        Fetch<BEntity, CEntity> blocks = pages.fetch(BEntity_.cEntityList, JoinType.LEFT);
        Fetch<CEntity, DEntity> rules = blocks.fetch(CEntity_.dEntityList, JoinType.LEFT);

        Predicate idPredicate =
            criteriaBuilder.equal(criteriaBuilder.literal(AEntity_.id), criteriaBuilder.literal(id));

        query.where(idPredicate);

        return entityManager.createQuery(query).getSingleResult();

Wondering what options i have as a workaround to still load all related records in B, C & D preferably using the criteria API? Is this even possible? Do i need to create a separate query?

Thanks in advance.

Bend
  • 304
  • 1
  • 2
  • 15
  • Please check the below references which uses multiple queries instead one query to solve multiplebagfetchexception https://stackoverflow.com/questions/66196630/build-criteria-api-query-to-avoid-multiplebagfetchexception . – Madhawa Gunasekara Apr 20 '23 at 01:30
  • 1
    @madhawaOnline thanks for the suggestion, i would do this if all of the related records i wanted to fetch were inside my AEntity, however they are all nested inside each other like Russian nesting dolls. How would i do it in this case? – Bend Apr 20 '23 at 02:50

0 Answers0