Eslam Tahoon
Eslam Tahoon

Reputation: 2313

JPA Specification Use sum with Join

I have an Entity Called Unit, and other one Called PriceElement

where

@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;

}

I would like to filter units which sum of total property of it's priceElements between a specific range

Upvotes: 0

Views: 1950

Answers (1)

JLazar0
JLazar0

Reputation: 1292

You could try filtering using a subquery as follows:

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

Another option (only with JPA 2.1 is add the condition of the subquery in the inner join clause)

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

Upvotes: 1

Related Questions