我使用JPA查询条件在同一个表上构建一个带连接的查询。该表如下所示。
Table A
Id EventType
A Start
A Start
A End
B Start
C Start
C End
我想查找EventType为Start且没有相同Id的EventType End的所有行。 在SQL中:我通过下面的连接得到了这个:
select DISTINCT *
from (select *
from A
where Id='A'
AND EventType = 'Start') startEventTable
LEFT JOIN (select *
from A
where Id='A'
AND EventType = 'endEvent') endEventTable
ON (startEventTable.Id = endEventTable.Id)
WHERE endEventTable.Id IS NULL;
我在JPA中无法实现这一点
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(A.class);
Root<A> r1 = cq.from(A.class);
SubQuery sq1 = cq.subquery(A.class);
SubQuery sq2 = cq.subquery(A.class);
Root<A> r2 = sql.from(A.class);
Root<A> r3 = sq2.from(A.class);
sq1.where(<predicate>);
sq2.where(<predicate>);
cq.where(cb.and(cb,exists(sq1), cb.exists(sq2).not()));
New TypedQuery(cq).getResultList();
这会因多个路径异常而失败。我是JPA查询的新手,请求有人在这里提供帮助。
答案 0 :(得分:0)
您可以在JPA中表达等效查询:
SELECT *
FROM A
WHERE Id='A' AND EventType = 'Start'
AND Id NOT IN (
SELECT Id from A
WHERE Id='A'
AND EventType = 'endEvent')
使用this方法。
答案 1 :(得分:0)
使用以下更简单,更快速的查询之一:
SELECT DISTINCT * -- you probably don't need DISTINCT
FROM A
WHERE Id = 'A'
AND EventType = 'Start'
AND NOT EXISTS (
SELECT 1
FROM A a1
WHERE a1.Id = A.Id
AND EventType = 'endEvent'
);
或者
SELECT DISTINCT * -- you probably don't need DISTINCT
FROM A
LEFT JOIN A a1 ON a1.Id = A.Id
AND a1.EventType = 'endEvent'
WHERE A.Id = 'A'
AND A.EventType = 'Start'
AND a1.Id IS NULL;
详细说明: