JPA 规范将 sum 与 Join 结合使用

JPA Specification Use sum with Join

我有一个名为 Unit 的实体,另一个名为 PriceElement

哪里

@Entity
public class Unit {

  //

  @OneToMany(mappedBy = "unit", cascade = CascadeType.ALL, orphanRemoval = true)
  private Set<PriceElement> priceElements;

}

@Entity
public class PriceElement {

  //

  private Integer total; 

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "unit_Id")
  private Unit unit;

}

我想过滤 priceElements 总和 属性 在特定范围

之间的单位

您可以尝试使用子查询进行过滤,如下所示:

//Initialize criteriaBuider and CriteriaQuery
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Unit> cq = cb.createQuery(Unit.class);

//Define Query
Root<Unit> rootUnit = cq.from(Unit.class);

//Create Subquery to get the sum
Subquery<Integer> sqSum = cq.subquery(Integer.class);
Root<PriceElement> rootSQPrice = sqSum .from(PriceElement.class);
Join<PriceElement,Unit> joinSQUnit = rootSQPrice.join(PriceElement_.unit);

//Set the condition, the unit of the subquery is the same as the unit of the main query
sqSum.where(cb.equals(joinSQUnit.get(Unit_.id),rootUnit .get(Unit_.id)))

//Set te result of the subquery as sum of totals
sqSum.select(cb.sum(rootSQPrice.get(PriceElement_.total)));

//Add the result of the subquery in query where clause
cq.where(cb.between(sqSum,Range0,Range1));

cq.select(rootUnit);

另一个选项(只有 JPA 2.1 是在内部连接子句中添加子查询的条件)

Root<Unit> rootUnit = cq.from(Unit.class);
Join<Unit,PriceElement> joinPrice = rootUnit.join(Unit_.priceElements);
//Id condition is implicit in the initialization of the join, add between condition
joinPrice.on(cb.and(cb.between(sqSum,Range0,Range1)))