Group by trunced date in JPA

时间:2018-02-26 17:38:42

标签: postgresql jpa hql specifications

I need help!

I need to build specification for

SELECT date_trunc('day', start_time)
FROM Example
GROUP BY date_trunc('day', start_time)

(PostgreSQL)

I have code:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = cb.createQuery(Object[].class);

Root<Example> root = query.from(Example.class);

Expression<Date> exp = cb.function("date_trunc", Date.class , cb.literal("day"), root.get("startTime"));

List<Object[]> result = entityManager.createQuery(query.select(exp).groupBy(exp)).getResultList();

But I get the exeption:

Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2122)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1905)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1881)
    at org.hibernate.loader.Loader.doQuery(Loader.java:925)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
    at org.hibernate.loader.Loader.doList(Loader.java:2622)
    at org.hibernate.loader.Loader.doList(Loader.java:2605)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2434)
    at org.hibernate.loader.Loader.list(Loader.java:2429)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1339)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
    ... 122 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: column "examplei0_.start_time" must appear in the GROUP BY clause or be used in an aggregate function
  Position: 69

What do I do wrong?

hibernate sql:

select date_trunc(?, examplei0_.start_time) as col_1_0_ from examplei0_ group by date_trunc(?, examplei0_.start_time)

It works if I execute it in Database console.

0 个答案:

没有答案