简体   繁体   中英

Hibernate entity with more than two OneToMany fields

I have the following hibernate entity:

@Entity
public class Customer {

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Address> addresses = new ArrayList<>();

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Contact> contacts = new ArrayList<>();

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Name> names = new ArrayList<>();

    // Many more, including a primary key
}

Starting the application, I got the following exception:

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

If I remove one arbitary OneToMany association, or if I add a @Fetch(value = FetchMode.JOIN) to an arbitary OneToMany association, everything works fine.

Is this a hibernate bug, a hibernate limitation, or is there anything wrong with my entity? TIA!

It is not a bug. It is because of Hibernate uses a one select with a join to fetch all the data. Hibernate can join three and more tables, but the result of joining will have duplicates of, for example, Address columns. Hibernate needs to remove duplicates — it is a reason why Set works.

Possible workarounds:

  • Use Set<Address> instead of List<Address> . You should use Set for all collections.
  • Use lazy fetching fetch = FetchType.LAZY
  • Use @Fetch(value = FetchMode.SUBSELECT)

Some additional reading:

A beginner's guide to Hibernate Set and List behavior

Hibernate does not return distinct results for a query with outer join fetching enabled for a collection (even if I use the distinct keyword)?

Try to use:

@OneToMany
@LazyCollection(value=LazyCollectionOption.TRUE)
private Collection<Name> names = new ArrayList<>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM