Solutions to the exception of cannot simply fetch multiple bags

Knowledge map advanced must read: read how large-scale map data efficient storage and retrieval>>>

The exception information is as follows:

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


When did the problem arise

When an entity object contains more than one non lazy acquisition policy, such as @ onetomany, @ manytomany or @ elementcollection, the acquisition policy is (fetch = fetchtype. Eager)

Causes of the problem:

When there is more than one (fetch = fetchtype. Eager), the persistence framework grabs one party’s objects and loads the multi-party objects into the container at the same time, and the multi-party objects may be associated with other objects. In JPA implemented by hibernate, the default maximum grabbing depth is level 4 (it has a property configuration of 0-3). If there are duplicate values in the multi-party (Level 2), the, Then the values captured in the third level cannot be mapped, and multiple bags will appear


1. Change (fetch = fetchtype. Eagle) to (fetch = fetchtype. Lazy)

2. Modify the list to set set, that is, recommend the many side of @ manytomany or @ onetomony to store it in set container instead of list set

3. Change the fetchmode to @ fetch (fetchmode. Subselect), that is to say, send another select statement to capture the associated entities of all the previously queried entity objects

4. Add @ indexcolumn to the corresponding attribute. This annotation allows you to specify the field where the index value is stored, just as the set container does not allow duplicate elements

Recommended treatment:

Method 2

Methods 3 and 4 are unique to hibernate and are not JPA standard

If method 1 can be used, this problem will not occur


Similar Posts: