Hibernate HQL和使用分组获取

时间:2011-05-16 18:36:49

标签: hibernate hql

我们有一个hibernate pojo Reporting / ReportingID,它有几个包含计数,日期,操作和设备的属性。设备属性映射到名为Device的hibernate pojo(注意:我希望它能够获取设备,所以我不必单独查询它)。

所以我的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子句中列出设备表中的每一列,这看起来很古怪?

1 个答案:

答案 0 :(得分:0)

书写

group by something

在HQL中,something是一个实体被翻译成

group by entity_id1, entity_id2 ...
SQL中的

entity_id1entity_id2等是实体的 id 属性所映射的列。如果是简单(而不是复合/组件)标识符,则只有一列。

这适用于常规查询,并为“连接提取”选择提出了明显的问题。没有解决方法 - 您需要在group by下单独列出所有属性。

另一种方法(可能适用或不适合 - 不知道更多关于您的模型的说法)是避免使用连接提取而是缓存您的实体(通过会话和/或二级缓存)从而检索(和分组)只有实体ID。