小编典典

与休眠中的其他字段一起计数

hibernate

我想用hibernate返回一组中其他字段的行 ,而我的实体类中没有任何字段代表计数。例如我有一个付款实体类:

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

    // other fields and setter/getters
}

sql查询:

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

和我的hibernate标准:

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

如我所说,我的问题是我不知道在哪里/如何访问count的值(来自criteria.list())!


阅读 296

收藏
2020-06-20

共1个答案

小编典典

我认为这是您代码的正确版本:

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