HQL / JPQL - 在FROM上嵌套选择

时间:2011-08-05 16:49:30

标签: sql nhibernate hql jpql

我尝试将我的SQL查询转换为HQL或JPQL(我想从对象映射中受益)。

我的SQL请求是:

SELECT * 
FROM (SELECT bde, MAX(creation_date) 
      FROM push_campaign GROUP BY bde) temp, 
push_campaign pc where pc.bde = temp.bde and pc.creation_date = temp.creation_date;

我尝试(不成功)在JPQL中将其转换为:

select pc 
from (select bde, max(creationDate) 
      from PushCampaign group by bde) temp, 
PushCampaign pc 
where pc.bde = temp.bde and pc.creationDate = temp.creationDate

但我得到了成长:

IllegalArgumentException occured :
     

org.hibernate.hql.ast.QuerySyntaxException:意外令牌:(近   第1行,第16列[从中选择pc(选择id,max(creationDate))   models.PushCampaign group by bde)temp,models.PushCampaign pc where   pc.id = temp.id]

我读过嵌套的select只能在select或where子句中。

您是否有解决方法来保持对象映射的请求和好处?

3 个答案:

答案 0 :(得分:3)

这应该得到类似的结果

select pc
from PushCampaign pc 
where pc.creationDate =
(select max(creationDate) from PushCampaign inner where inner.bde = pc.bde)

答案 1 :(得分:3)

单个请求中无法使用JPQL或HQL。

要在一个请求中执行此操作,我建议:

String campaignToLaunch = "select pc.* from PushCampaign pc ..."
//SQL request which return a resultset compatible with the models.PushCampaign class
Class className = Class.forName("models.PushCampaign");
List<PushCampaign> result = JPA.em()
                           .createNativeQuery(campaignToLaunch,className)
                           .getResultList();

答案 2 :(得分:2)

一个简单的解决方案可能是:

servlet
{
    Query q = entityManager.createNativeQuery("SQL");
    List<> li =  q.getResultList();

    @PersistenceContext(unitName="UNIT")
    private EntityManager entityManager;
}