I'm using JPA Query Criteria to build a query with a join on the same table. The table looks like below.
Table A
Id EventType
A Start
A Start
A End
B Start
C Start
C End
I want to find out all rows whose EventType is Start and does not have EventType End for the same Id. In SQL: I got this with joins like this below:
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;
I could not realize this in 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();
This fails with multiple path exceptions. I'm new to JPA queries, request someone to help here.