JPA спецификация Используйте сумму с Join - PullRequest
0 голосов
/ 08 июля 2019

У меня есть Entity Called Unit, а другой называется Calle 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 находится в определенном диапазоне

1 Ответ

1 голос
/ 10 июля 2019

Вы можете попробовать выполнить фильтрацию с помощью подзапроса следующим образом:

//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)))
...