我正在尝试编写一个相当复杂的JPQL语句,该语句根据另一个表中的值对结果进行排序。我知道MySQL会是什么样子,但我需要把它变成JPQL。这是等效的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
任何有关如何做到这一点的帮助将非常感激。具体来说,我似乎遇到了这个部分的问题:
ON ppp.Event_ID = o.Event_ID AND ppp.Event_Set_ID = o.Event_Set_ID
所以,我已经尝试过了:
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 " +
"";
如果我尝试添加类似
的内容WHERE ...
AND o.eventSetID = ppp.eventSet
......它根本不起作用。如果我查看生成的SQL,看起来就像忽略了ppp.eventSet。
连连呢?
答案 0 :(得分:0)
所以,首先要感谢评论的海报,询问我的实体关系。这迫使我仔细研究事物并意识到错误。
事实证明,当我在JPA比现在更糟糕时,我将o.eventID属性设置为实际的Integer,就像在记录/对象的主键中,而不是实际的对象。因此,在上面的JPQL中,我实际上是在尝试将对象映射到以下语句中的整数:
AND o.eventID = ppp.event
结果是正确的陈述是:
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.eventID" +
" order by ppp.seqNum ASC" +
"");
虽然我最终应该在Observation类中更改实际转到对象的关系。