Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join Fetch for One To Many relationship is returning same entity multiple times

I have the following mapping
1 User can have 0 or more roles.

Query
from User u JOIN Fetch u.roles

If User1 has two roles RoleA and RoleB.
Then User1 is returned twice.

What i expect is User1 should be returned Once with list of roles containing RoleA and RoleB
How can I fix this.

Also please explain behavior for Many To Many relationship.

like image 723
Piyush Avatar asked Sep 08 '25 15:09

Piyush


1 Answers

See the JPA spec 4.4.5.3

SELECT d FROM Department d LEFT JOIN FETCH d.employees WHERE d.deptno = 1 

A fetch join has the same join semantics as the corresponding inner or outer join, except that the related objects specified on the right-hand side of the join operation are not returned in the query result or otherwise referenced in the query. Hence, for example, if department 1 has five employees, the above query returns five references to the department 1 entity.

Options

  1. You can add a DISTINCT to the SELECT clause to filter out the duplicate rows.
  2. Define an EntityGraph for the query and add the roles field to it, and it will be fetched, meaning you omit the "FETCH JOIN" from the query.
  3. Mark the roles field as EAGER, but this would then apply to all fetching of that field, so likely not desirable.
like image 77
Neil Stockton Avatar answered Sep 10 '25 06:09

Neil Stockton