Arya
Arya

Reputation: 3029

count with other fields in group by with hibernate

I want to return count of rows with some other fields in a group by with hibernate, and i have not any field in my entity class representing count. for example i have a Payment entity class:

class Payment
{
    private Long id;
    private String totalCode;
    private String activityCode;
    private Long amount;

    // other fields and setter/getters
}

sql query:

select count(*), sum(p.amount), p.total_code, p.activity_code 
from  tb_payment p
group by p.total_code,p.activity_code

and my hibernate criteria:

Session session = getCurrentSession();
ProjectionList projectionList = Projections.projectionList();        
projectionList.add(Projections.groupProperty("totalCode"))
        .add(Projections.groupProperty("activityCode"))
        .add(Projections.sum("amount"))
        .add(Projections.count("id"));
Criteria criteria  = session.createCriteria(Payment.class);
criteria.setProjection(projectionList);
List<Payment> payments = criteria.list();

As i said, my problem is i don't know where/how can i access the value of count (from criteria.list())!?

Upvotes: 3

Views: 9613

Answers (1)

dened
dened

Reputation: 4310

I think here is the correct version of your code:

Session session = getCurrentSession();
ProjectionList projectionList = Projections.projectionList();        
projectionList.add(Projections.groupProperty("totalCode"))
        .add(Projections.groupProperty("activityCode"))
        .add(Projections.sum("amount"))
        .add(Projections.rowCount());
Criteria criteria  = session.createCriteria(Payment.class);
criteria.setProjection(projectionList);
List<Object[]> payments = criteria.list();
for (Object[] payment : payments) {
    System.out.println("totalCode: " + payment[0]);
    System.out.println("activityCode: " + payment[1]);
    System.out.println("amountSum: " + payment[2]);
    System.out.println("rowCount: " + payment[3]);
}

Upvotes: 6

Related Questions