我想用冬眠返回一组中其他字段的行数,而我的实体类中没有任何字段代表计数.例如我有一个付款实体类:
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())!
解决方法:
我认为这是您代码的正确版本:
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]);
}