我在一个非常简单的项目上使用 EclipseLink(2.4、2.5 和 2.6),我有一个 Department
实体,每个 Department
链接到一个 Employee
实体,它是 Department
的 manager
。
我目前无法使这个简单的查询工作:
select d from Department d where d.manager is null
返回 1 行
select d from Department d left join fetch d.manager where d.manager is null
返回 0 行
我在 H2 数据库上使用 Eclipselink。生成的 SQL 查询似乎没有创建左连接,而是创建了一个显然会失败的内部连接。
SELECT t1.ID, t1.MANAGER_ID, t0.ID, t0.NAME FROM EMPLOYEE t0, DEPARTMENT t1
WHERE ((t1.MANAGER_ID IS NULL) AND (t0.ID = t1.MANAGER_ID))
这是一个错误还是需要的东西?或者有人可以帮我解决这个问题吗?
如果有人需要,我们很乐意提供代码和示例,或者提供更多信息。
最佳答案
使用 FETCH JOIN
引用查询中作为副作用返回的实体似乎不安全。 JPA 规范试图至少针对多值关联(JSR 338,第 4.4.5.3 节)禁止此类查询:
It is not permitted to specify an identification variable for the objects referenced by the right side of the
FETCH JOIN
clause, and hence references to the implicitly fetched entities or elements cannot appear elsewhere in the query.
您在 EclipseLink 和 Hibernate 上执行的查询产生了不同的结果(EclipseLink 2.6.3:没有结果,Hibernate 4.3.11:所有部门都没有经理):
select d from Department d left join fetch d.manager where d.manager is null
要解决您的问题,可以使用子查询。可移植的 JPQL 查询可能如下所示(在 EclipseLink 和 Hibernate 中结果相同):
select d1 from Department d1 left join fetch d1.manager where exists
(select d2 from Department d2 where d2.manager is null and d1 = d2)
关于java - JPA:左连接不适用于 where 子句中的 "is null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25509686/