count with other fields in group by with hibernate

只谈情不闲聊 提交于 2019-12-02 10:57:39

问题


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())!?


回答1:


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]);
}


来源:https://stackoverflow.com/questions/23044565/count-with-other-fields-in-group-by-with-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!