Multiple Bags Exception / Searching multiple collections with JPA

Asked

Viewed 47 times

0

I’m having a problem with JPA when I make an appointment.

I’d like to consult Entity A that has a List of Entity B and List of Entity C (I want to consult Entity A bringing the relationships with Entities B and C into one query).

When I try to execute this query the exception of Multiple bags is launched.

Is there any way to do this consultation without having to use @IndexColumn, Fetch.EAGER or change List for Set? (Solutions I found on the internet)

NOTE: I did not put the code here because I just want to know if there is an alternative other than the ones I mentioned earlier.

  • I already did, and thanks to whoever voted negative ;)

1 answer

0

The most common cause for this error is when you try to make 2 (or more) JOINs using FETCH, each of these JOINis by means of a List.

Let’s take an example. Given the (pseudo) entities:

@Entity
class Entidade1 {
    private List<Entidade2> entidades2;
}

@Entity
class Entidade2 {
    private List<Entidade3> entidades3;
}

The following JPQL will reproduce the problem:

SELECT e1 FROM Entidade1 e1
JOIN FETCH e1.entidades2 e2
JOIN FETCH e2.entidades3 e3

The most common solution is this: changing from List for Set the mapping of entidades2 and entidades3. The solution with EAGER I wouldn’t even consider, such a consequence that it can bring to the application.

Or, if possible, avoid using a JOIN FETCH from another. As far as I know, only Hibernate supports alias in JOIN FETCH, allowing this type of situation and error.

Thus, the solution that I recommend is to consider the use of a VO, bringing only what you need from the 3 entities:

SELECT new br.com.EntidadeVO(e1.id, e1.nome, e2.id, e3.nome) FROM Entidade1 e1
JOIN e1.entidades2 e2
JOIN e2.entidades3 e3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.