如何将SQL查询转换为休眠查询

时间:2019-05-13 07:08:21

标签: sql-server hibernate jpa

我有q sql查询,其中我正在使用子查询和左联接来获取数据。它在sql服务器上正常工作,但是当我在使用HQL的休眠模式下使用此查询时,它说出意外的标记(;

以下是我的查询,该查询在sql服务器上运行正常-

SELECT IH.vendorName, IH.C, IHP.CP FROM (SELECT vendorName, count(*) as C 
FROM InvoiceHeader GROUP BY vendorName) IH LEFT JOIN (SELECT vendorName, 
count(*) AS CP FROM InvoiceHeader WHERE invoiceStatus='Processed' GROUP BY 
vendorName) IHP ON IHP.vendorName=IH.vendorName ORDER BY IH.C DESC

在这里,我试图将我的sql查询转换为HQL

Query q = sessionFactory.getCurrentSession().createQuery("SELECT 
IH.vendorName, IH.C, IHP.CP FROM (SELECT vendorName, count(*) as C FROM 
InvoiceHeader GROUP BY vendorName) IH LEFT JOIN (SELECT vendorName, count(*) 
AS CP FROM InvoiceHeader WHERE invoiceStatus='Processed' GROUP BY 
vendorName) IHP ON IHP.vendorName=IH.vendorName ORDER BY IH.C DESC"); 

但我在此错误

org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:41: unexpected token: (
org.hibernate.hql.internal.ast.ErrorCounter reportError
ERROR: line 1:61: unexpected token: count

1 个答案:

答案 0 :(得分:0)

这里是部分方法。

首先,您的查询需要简化,因为联接根本没有效率。 MSSQL不支持FILTER,但是Modern SQL向我们展示了一种足够的选择。

SELECT vendorName, sum(case when invoiceStatus = 'Processed' then 1 end) as CP, count(*) as C FROM InvoiceHeader GROUP BY vendorName ORDER BY C DESC;

第二,如果事实证明无法将其翻译为HQL,则可以使用createNativeQuery,但这是我的尝试:

SELECT I.vendorName, COUNT(I) as C, SUM(CASE WHEN I.invoiceStatus = 'Processed' THEN 1 END) AS CP FROM InvoiceHeader I GROUP BY I.vendorName ORDER BY C DESC

使用表别名很重要,即使它是唯一的表,也可以在查询中正确解析。