Chose grouping based on parameter in Hibernate named query

时间:2015-05-04 19:39:56

标签: java sql oracle hibernate

I have a Hibernate Named Query that I've defined in an XML configuration.

The query generates an aggregate report on person's demographic information. Where we live, that person could live in a province or a county.

I'm wondering if it's possible to aggregate the query by either province or county, based on a hibernate query parameter.

Here's what I've tried:

SELECT to_char(case when :groupReportBy = 'province' then PROVINCE else COUNTY end),
     COUNT(distinct PERSON_TABLE.PERSON_ID) as {personReport.numOfPeople}
     --, There are some other aggregation things that happen here as well
FROM 
  PERSON_TABLE PI
WHERE
  PI.BDATE >= date '2014-01-01' and PI.BDATE <= date '2014-12-31'
GROUP BY 
  case when :groupReportBy = 'province' then PROVINCE else COUNTY end);

The parameter name is :groupReportBy. This query will work if I hard code 'province' instead of the parameter name but If I run it as it appears above, I get the following error:

ORA-00979: not a GROUP BY expression
00979. 00000 -  "not a GROUP BY expression"
*Cause:    
*Action:

I execute the query from my Java code like this:

private List getReport (String namedQuery, String groupReportBy) {

    Session session = sessionFactory.getCurrentSession();
    Query query = session.getNamedQuery(namedQuery);

    query.setParameter("reportBy", reportBy);

    return query.list();
}

I'm using an Oracle Database.

I'd really prefer not to have to re-write these queries using the Criteria API. They're actually super duper long and there's a lot of them.

Is there a way to do this in SQL?

1 个答案:

答案 0 :(得分:0)

我从未使用组参数对其进行测试,但我认为它的行为与JPQL / HQL查询的其他部分相同。 NamedQueries是预编译的,因此除了参数之外,以后不能更改。

我花了2分钟看了JPA规范,但没有找到可以在运行时修改的确切定义。所以以下可能不是100%正确,但应该足够你了。

JPQL / HQL关键字和模型对象属性在运行期间无法在NamedQuery中更改,原因可能是查询转换为基于对象的表示形式。因此,您需要编写标准的JPQL / HQL查询。