使用Hibernate投影对聚合函数执行算术运算

时间:2014-03-20 06:02:06

标签: sql hibernate hibernate-4.x

我正在使用Hibernate 4,我需要对聚合函数进行算术运算。我想使用投影来实现这一目标。我想要获得的等效MySQL查询是:

select sum(c)/sum(bs) from my_data where pid=6 group by DATE(event_timestamp)

到目前为止,我可以通过使用以下内容获得总和(c):

List result= session.createCriteria(MyData.class)
                    .add(Restrictions.ge("eventTimestamp",fromDate)
                    .add(Restrictions.le("eventTimestamp",toDate)
                    .add(Restrictions.eq("property",p)
                    .setProjection(Projections.projectionList()
                                .add(Projections.sum("c"))
                                .add(Projections.sqlGroupProjection("date(evet_timestamp) as eventDate","eventDate",new String[]{"eventDate"},new Type[]{StandardBasicType.DATE})))
                    .addOrder(Order.asc("eventTimestamp"));

我可以使用此sum(c),但正如您现在所见,我希望sum(c)/sum(bs)作为结果。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

您可以使用Projections.sqlProjection引入所需字段并计算字段值。查看此处的示例

http://technofes.blogspot.com/2011/08/hibernate-examples-step-5.html

更新

add(Projections.sqlProjection("sum(c)/sum(bs) AS res",
            new String[] { "res" }, new Type[] {Hibernate.INTEGER }));