标准有一种方法可以返回发票列表以及该发票的总付款。
理论上,答案是您可以在投影查询中使用分组属性将结果分组为按发票支付的总金额。第二部分是您可以在 Invoice 上使用瞬态“totalPayment”值,并使用转换器选择投影到 Invoice 结构中。这比处理具有不同属性的 ArrayList 更容易,但取决于您需要将结果用于什么目的。
为了证明这一点,这里是一个小型 Invoice 类的重要部分:
public class Invoice{
private String name;
@Transient private int totalPayments;
@OneToMany Set<Payment> payments = new HashSet<Payment>();
// getters and setters
...
}
那么这是您可以使用的标准
Criteria criteria = session.createCriteria(Invoice.class)
.createAlias("payments", "pay")
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("id"))
.add(Projections.property("id"), "id")
.add(Projections.property("name"), "name")
.add(Projections.sum("pay.total").as("totalPayments")))
.setResultTransformer(Transformers.aliasToBean(Invoice.class));
List<Invoice> projected = criteria.list();
这是生成的sql
Hibernate:
select this_.id as y0_,
this_.id as y1_,
this_.name as y2_,
sum(pay1_.total) as y3_
from invoice this_
inner join invoice_payment payments3_ on this_.id=payments3_.invoice_id
inner join payment pay1_ on payments3_.payments_id=pay1_.id
group by this_.id