特定日期的休眠标准聚合

时间:2015-01-05 01:22:35

标签: hibernate

如何将此查询转换为休眠标准:

Select cat, sum(amount) 
from transaction 
where customer =: customer 
  and month =: month 
  and year = year 
group by cat; 

我目前的标准是:

 Select cat, sum(amount) 
 from transaction 
 where customer =: customer 
 group by cat; 

Criteria cx = getCriteria()
         .setProjection(Projections.projectionList()
                .add(Projections.sum("amount", "amount")
                .add(Projections.groupProperty("cat", "cat")
                )
        .add(Restrictions.eq("customer", customer))
                ;

我尝试了很多这样的屁股.add(Restrictions.eq(" month(createOn)",month)但我收到了这个错误:

org.hibernate.QueryException: could not resolve property: month(createOn) of: com.transaction

我确保我的createOn字段的数据类型为date,并且没有语法错误。

1 个答案:

答案 0 :(得分:0)

使用Sql Restictions Restrictions.sqlRestriction

Criteria cx = getCriteria()
     .setProjection(Projections.projectionList()
            .add(Projections.sum("amount", "amount")
            .add(Projections.groupProperty("cat", "cat")
            )
    .add(Restrictions.eq("customer", customer))
    .add(Restrictions.sqlRestriction("YEAR(DB_DATE_COLUMN) >= ? ", year,Hibernate.INTEGER)
    .add(Restrictions.sqlRestriction("MONTH(DB_DATE_COLUMN) >= ? ", month,Hibernate.INTEGER)   ;