Diego Krupitza
Diego Krupitza

Reputation: 121

Hibernate 5.2.11 - Multiple simultaneously Featch.Eager

I have a class witch has 4 Lists with a @*toMany annotation:

    public class Component {

            @OneToMany(mappedBy = "component", orphanRemoval = true, cascade = CascadeType.ALL, targetEntity = ComponentHistoric.class)
            //@OnDelete(action = OnDeleteAction.CASCADE)
            @LazyCollection(LazyCollectionOption.FALSE)
            private List<ComponentHistoric> componentHistoricList;

            @ManyToMany(targetEntity = Organization.class)
            @LazyCollection(LazyCollectionOption.FALSE)
            private List<Organization> organizations;

            @OneToMany(targetEntity = ComponentPerson.class, cascade = CascadeType.ALL)
            @LazyCollection(LazyCollectionOption.FALSE)
            private List<ComponentPerson> componentPeople;

            @OneToMany(targetEntity = ComponentLink.class, cascade = CascadeType.ALL)
            @LazyCollection(LazyCollectionOption.FALSE)
            private List<ComponentLink> componentLinks;
    }

It is not possible to use a Set<> instead of the Lists. When I use featch = Featch.Eager. I get the exception (Number 1). The currently version above I get the exception (Number 2).

Exception (Number 1): org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

-

Exception (Number 2): org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: xxxx.xxxxx.xxxx.ComponentHistoric.componentHistoricVersion, could not initialize proxy - no Session

Upvotes: 1

Views: 484

Answers (2)

v.ladynev
v.ladynev

Reputation: 19956

You didn't add

@LazyCollection(LazyCollectionOption.FALSE)

to the xxxx.xxxxx.xxxx.ComponentHistoric.componentHistoricVersion

A better way is always use lazy loading and load necessary association with Hibernate.initialize(), join fetch etc., because you will not be able to disable eagerly loading of associations with @LazyCollection.

Upvotes: 1

Simon Martinelli
Simon Martinelli

Reputation: 36103

Exception Number 1:

This is a limitation of Hibernate that does not support more than one eager loaded List in an entity.

Exception Number 2:

When your list is accessed outside the transaction boundary you get this exception. So you must initialize this collection before you use it.

There are many option to do so:

  • Call the getter or iterator on the collection
  • Use Hibernate.initialize() and pass the collection as parameter
  • Use join fetch in a query when loading the entities with a query

Upvotes: 2

Related Questions