【发布时间】:2016-03-18 23:47:09
【问题描述】:
我想在 Postgres 9.4 数据库系统上通过 JPA 2.0 和 Hibernate 4.2.21 版本执行本机 SQL 查询。
基本上,根据我在stackoverflow 上的最新post,我尝试将大量对象/记录放入“临时”存储桶中。
设置可以简化为以下设置,其中包含一个带有 id 字段和给定时间戳的表“MyObject”:
CREATE TABLE myobject
(
id bigint NOT NULL,
lastseen timestamp without time zone,
)
我应该执行查询的代码是这个:
Query q = getEntityManager().createNativeQuery(
"select count(id),date_part('day', :startDate - c.lastseen) AS " +
"difference from myobject c " +
"group by date_part('day', :startDate - c.lastseen) order by difference asc");
q.setParameter("startDate", startDate);
List<Object[]> rawResults = q.getResultList();
//process the reuslts
通过 pgAdmin3 使用示例日期执行此查询会按预期返回结果。
但是,如果我尝试通过 Hibernate 作为本机查询执行相同的查询,则会失败并出现以下异常:
Caused by: org.postgresql.util.PSQLException: FEHLER: column „myobject.lastseen“ must appear in the group by clause or be used in an aggregate function Position: 40 at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:420) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:305) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79) ... 94 more
此异常似乎有效且不言自明,但为什么我可以通过 PgAdmin3 执行相同的查询? Hibernate SQL 解析器是否比 pgAdmin3 更严格,还是它弥补了一些错误?
那么如何制定我的 SQL 查询以使其通过 Hibernate 可执行?
编辑:
由于某种原因,以下 SQL 语句(带有显式子选择)通过 PgAdmin3 以及通过 Hibernate 工作:
select count(id), difference
from (select c.id,c.lastseen,date_part('day', :startDate - c.lastseen) AS difference
from myobject c) AS temporalBucket
group by difference
order by difference asc
但这仍然不能回答给定代码片段中上一个查询的问题。
【问题讨论】:
标签: java sql hibernate postgresql jpa