我希望通过hibernate返回组中其他字段的 count 行,并且我的实体类中没有任何字段表示count。例如,我有一个支付实体类:
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
和我的休眠标准:
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())!?
答案 0 :(得分:3)
我认为这是您的代码的正确版本:
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]);
}