Criteriaには、請求書のリストとその請求書の合計支払い額を返す方法があります。
理論的には、その答えは、予測クエリでグループ化プロパティを使用して、結果を請求書ごとの合計支払いにグループ化できるということです。2番目の部分は、請求書で一時的な「totalPayment」値を使用し、トランスフォーマーを使用して請求書構造への投影を選択できることです。これは、さまざまなプロパティのArrayListを処理するよりも簡単ですが、結果を何に使用する必要があるかによって異なります。
これを実証するために、小さな請求書クラスの重要な部分を次に示します。
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