【问题标题】:JPA query additional group byJPA 查询附加分组依据
【发布时间】:2011-12-28 04:56:01
【问题描述】:

如何为下面的 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: not a GROUP BY expression”


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 (SELECT MAX(t1.SENDTIME) FROM OPSTATUS t1 WHERE (t1.OPERATIONTYPE = ? AND t1.RECEIVEDFLAG = ?) GROUP BY t1.DN)) GROUP BY t2.DN [params=? , ?, ?, ?]


如何防止附加“分组依据”?我尝试添加 'order by o.sendtime' 没用。

【问题讨论】:

    标签: jpa openjpa


    【解决方案1】:

    您的意思是选择每个 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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多