JPA查询附加组

时间:2011-12-28 04:56:02

标签: jpa openjpa

如何为下面的SQL编写JPA查询?


select * from opstatus o where o.OPERATIONTYPE=2 and o.RECEIVEDFLAG =2 and o.SENDTIME in (select max(o1.SENDTIME)from opstatus o1 where (o1.OPERATIONTYPE=2 and o1.RECEIVEDFLAG =2) group by o1.dn);

尝试运行以下查询


result = em.createQuery("select o from DTO o where "
+ "o.operationType=:operationType"
+ " and o.receivedFlag = :receivedFlag"
+ " and o.startTime in (select max(o1.startTime)from DTO o1 where   
o1.receivedFlag = :receivedFlag group by o1.Dn) order by o.startTime").
setParameter("operationType","2").
setParameter("receivedFlag", "2").getResultList();

然而,在运行时,下面的查询得到了生成,其中包含额外的'group by T2.DN',我们得到'org.apache.openjpa.persistence.PersistenceException:ORA-00979:不是GROUP BY表达式'


SELECT t0.OPERATIONID,t0.CURRENTSTEP,t0.DETAILEDSTEPS,t0.DN,t0.OPERATIONTYPE,t0.RECEIVEDFLAG,t0.REQUESTID,t0.SENDTIME from OPSTATUS t0,OPSTATUS t2 WHERE(t0.OPERATIONTYPE =?AND t0 .RECEIVEDFLAG =?AND t0.SENDTIME IN(选择MAX(t1.SENDTIME)来自OPSTATUS t1 WHERE(t1.OPERATIONTYPE =?AND t1.RECEIVEDFLAG =?)GROUP BY t1.DN))GROUP BY t2.DN [params =? ,?,?,?]


如何防止额外的'分组'被追加?我尝试添加'order by o.sendtime'没用。

1 个答案:

答案 0 :(得分:0)

您的意思是选择每个Dn组中的最后一个条目。如果两个不同的Dn具有相同的startTime,并且只有一个是最后一个(最大),则查询将失败。由于子查询中的o1未链接到外部o,OpenJPA将生成FROM OPSTATUS t0, OPSTATUS t2

也许您可以更改查询。

"select o from DTO o where "
+ "o.operationType=:operationType"
+ " and o.receivedFlag = :receivedFlag"
+ " and not exists (select o1 from DTO o1 where   
o1.receivedFlag = :receivedFlag and o1.Dn = o.Dn and o1.startTime > o.startTime) order by o.startTime"