Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Saturday

JPA(Java Persistence API) Tutorial -Handling the “cannot simultaneously fetch multiple bags” error

Handling the “cannot simultaneously fetch multiple
bags” error

This error happens when JPA retrieves an entity from the database and this entity has more than one list fields
marked for EAGERly fetching.
Check the code below:

import java.util.List;
import javax.persistence.*;
@Entity
public class Person {
@Id
private int id;
private String name;
@OneToMany(mappedBy = "person", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Car> cars;
@OneToMany(fetch = FetchType.EAGER)
private List<Dog> dogs;
// get and set
}

When a query to get the Person entity above is fired the following error message is displayed:
“javax.persistence.PersistenceException: org.hibernate.HibernateException: cannot simultaneously fetch multiple
bags”, a list can be known as bag.
This error happens because Hibernate (the specific JPA implementation farmework used for this example) tries to
bring the same result amount for each list. If the generated SQL returns 2 lines for the "dog" entity list and one for
the "car" entity list, Hibernate will repeat the "car" query to make the result equal. Check the images below to
understand what is happening when the entityManager.find(Person.class, person_id) command is executed:


There are four solutions for this situation:
•To use java.util.Set instead of other collection types => with this easy change the error can be
avoided.
•To use EclipseLink => it is a radical solution, but for JPA only users that use only JPA annotations
this change will have minimal impact.
•To use FetchType.LAZY instead of EAGER => this solution is a temporary solution, because if a
query fetches data from two collections this error may occur again. For example the following
query could trigger the error: “select p from Person p join fetch p.dogs d join fetch p.cars c”.
Additionally when using this approach the LazyInitializationException error may happen.
•To use @LazyCollection or @IndexColumn of the Hibernate implementation in the collection =>
it is a very good idea to understand how the @IndexColumn works and its effects when used, its
behavior will change varying to which side of the relationship it is added (the explanation of this
annotation is outside the scope of this mini book).

No comments:

Post a Comment