HQL / JPQL - FROM子句中的嵌套查询

7

我想将我的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: unexpected token: ( near line 1, column 16 [select pc from (select id, max(creationDate) from models.PushCampaign group by bde) temp, models.PushCampaign pc where pc.id = temp.id]

我了解到嵌套查询只能在select或where子句中使用。

您是否有解决方案来保留对象映射的请求和利益?


你尝试过使用 INNER JOIN 而不是在 WHERE 子句中进行连接吗? - Adriano Carneiro
我已经搜索了如何使用子查询和内连接的示例,但是找不到任何例子。我尝试过的所有测试都失败了...谢谢你的提示,我会朝那个方向深入研究。 - kheraud
在JPQL中,内部连接中不可能有子查询。只有在where或having语句中才可能存在。 - kheraud
3个回答

4

在单个请求中使用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();

3

这应该能够实现类似的结果。

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

实际上,我需要每个“bde”人口的单个记录。您的请求不允许这样做。而且,实际上不同/单个人口可以具有相同的creationDate。 - kheraud
@kheraud,您的答案可能更有效率,但我的查询确实会为每个bde返回一条记录。对于每条记录,子查询将仅查找当前bde的最大日期,因此子查询的结果因每条记录而异,应该返回正确的结果。试试看吧。 - Firo

2
一个简单的解决方案可能是:
servlet
{
    Query q = entityManager.createNativeQuery("SQL");
    List<> li =  q.getResultList();

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接