I’m trying to write a fairly complex JPQL statement that sorts results based on a value in another table. I know what the MySQL would look like, but I need help turning it into JPQL. Here’s the equivalent SQL:
SELECT o.* FROM Observation o
LEFT JOIN Obs_Event p
ON p.Event_ID = o.Event_ID
LEFT JOIN Event_Set ppp
ON ppp.Event_ID = o.Event_ID AND ppp.Event_Set_ID = o.Event_Set_ID
WHERE o.Individual_ID = <some id>
AND o.Observation_Date = <a date value>
ORDER BY ppp.Seq_Num ASC
Any help on how to do this would be much appreciated. Specifically I seem to having trouble with this part:
ON ppp.Event_ID = o.Event_ID AND ppp.Event_Set_ID = o.Event_Set_ID
So, far I’ve tried this:
Query q= em.createQuery("select o " +
" from Observation as o " +
" join o.eventID p" +
" join p.eventSetCollection ppp " +
" where o.individualID = :indiv " +
" AND o.observationDate = :d " +
" AND o.eventID = ppp.event " +
"";
If I try to add something like
WHERE ...
AND o.eventSetID = ppp.eventSet
… it simply doesn’t work. If I look at the generated SQL, it looks like ppp.eventSet is simply ignored.
Suggestions?
So, first thanks to the poster that commented, asking for my entity relationships. That forced me to take a closer look at things and realize what was wrong.
As it turns out, back when I was even worse at JPA than I am now, I set the o.eventID property to an actual Integer, as in the primary key of the record/object, instead of an actual object. Hence, in the JPQL above, I’m actually trying to map an object to an integer in the following statement:
AND o.eventID = ppp.event
turns out the correct statement is:
This works in a pinch, although I should eventually change that relationship in the Observation class to actually go to an object.