2011-05-16 84 views
1

我們有一個hibernate pojo Reporting/ReportingID,它有幾個包含計數,日期,操作和設備的屬性。設備屬性映射到一個名爲Device的hibernate pojo(注意:我希望它獲取設備,所以我不必單獨查詢它)。休眠HQL和分組提取

所以我有一個HQL,看起來像這樣:

"SELECT sum(report.deviceTotal), sum(report.settledPricePerDownloadExpense), report.id.device, avg(report.settledPricePerDownloadExpense), report.id.dCampaignActionTypeId " + 
"FROM Reporting report " + 
"WHERE report.id.dCampaignReportDate between :startDate and :endDate " + 
"AND report.id.dCampaignActionTypeId in (:actionIds) " + 
"AND report.id.dCampaign.dCampaignId in (:campaigns) " + 
"GROUP by report.id.dCampaignActionTypeId, report.id.device " + 
"ORDER by 1"; 

不過,我覺得,這將工作,但我得到這個錯誤:

Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Column 'dbo.device.device_id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197) 
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1493) 
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:390) 
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:340) 
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575) 
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400) 
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:179) 

我從這個得到的是爲我必須在group by子句中列出設備表中的每一列,這似乎是古怪的?

回答

0

寫作

group by something 
在HQL

其中something是一個實體被轉換爲

group by entity_id1, entity_id2 ... 

在SQL其中entity_id1entity_id2等方面都列到實體ID屬性映射。在簡單(而不是複合/組件)標識符的情況下,只有一列。

這適用於常規查詢,並提出了「加入提取」選擇的明顯問題。沒有解決方法 - 您需要在group by下單獨列出所有屬性。

另一種方法(可能或可能不適合 - 不知道更多關於你的模型的話不可能說)是避免使用聯合提取,而是緩存實體(通過會話和/或二級緩存)僅檢索(和分組)實體ID。

+0

我基本上使用標準而不是HQL工作,但團隊希望每個人都使用HQL。我想我會堅持標準,讓他們呻吟和呻吟。 – arinte 2011-05-17 13:44:05