Join Fetch for One To Many 关系多次返回同一个实体

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

我有以下映射
1 用户可以有 0 个或多个角色。

查询
来自用户 u JOIN Fetch u.roles

如果User1有两个角色RoleA和RoleB。
然后返回 User1 两次。

我期望的是 User1 应该返回一次,其中包含包含 RoleA 和 RoleB 的角色列表
我怎样才能解决这个问题。

另外请解释多对多关系的行为。

代码下方的用户:

criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

有关详细信息,请查看此 link: Hibernate Criteria returns children multiple times with FetchType.EAGER

参见 JPA 规范 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.

选项

  1. 您可以在 SELECT 子句中添加一个 DISTINCT 来过滤掉 重复的行。
  2. 为查询定义一个EntityGraph并向其添加roles字段, 它将被提取,这意味着您从查询中省略了 "FETCH JOIN"
  3. roles 字段标记为 EAGER,但这将适用于该字段的所有提取,因此可能不可取。