Pergunta

I am using Hibernate 4 and I need to have an arithmetic operation done on the aggregate function. I want to use projections to achieve this. The equivalent MySQL query that I am trying to get is this:

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

So far I could get the sum(c) by using the follwoing:

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"));

I am able to get sum(c) with this but as you can see now I want sum(c)/sum(bs) as the result. How can I do this?

Foi útil?

Solução

You can use Projections.sqlProjection to introduce desired field and calculate the field value. See an example here

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

UPDATE

add(Projections.sqlProjection("sum(c)/sum(bs) AS res",
            new String[] { "res" }, new Type[] {Hibernate.INTEGER }));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top