在hibernate聚合函数中使用函数作为参数

时间:2010-01-19 08:31:20

标签: java hibernate orm hql

我想在HQL中执行以下查询:

select count(distinct year(foo.date)) from Foo foo  

但是,这会导致以下异常:

  

org.hibernate.hql.ast.QuerySyntaxException:   期待CLOSE,发现'('近线   1,第27栏

似乎hibernate不允许使用函数作为其聚合函数的参数。有没有办法得到所需的结果?

2 个答案:

答案 0 :(得分:0)

  1. 选择整个日期
  2. 循环结果并从每个日期提取由年份构成的新集合
  3. 起初它听起来无效,但那只是一个额外的O(n),我猜N不是那么大。

    另一种方法是使用本机SQL查询。

答案 1 :(得分:0)

使用条件API可以使用sqlProjection

String func = format("count(distinct year(%s_.date))", criteria.getAlias());
String alias = "dateCol";
session.createCriteria(Foo.class).setProjection(
    sqlProjection(
        format("%s as %s", func, alias),
            new String[] { alias }, 
            new Type[] { Hibernate.LONG }
         )
     )
 );

这应该有效。我还没有测试过。

sql投影的唯一问题是你必须知道(即重复)列名。