【问题标题】:JPA Specification Use sum with JoinJPA 规范将 sum 与 Join 结合使用
【发布时间】:2019-11-18 08:11:26
【问题描述】:

我有一个实体叫 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 总属性总和的单位

【问题讨论】:

    标签: hibernate jpa spring-data-jpa jpa-2.0 jpa-2.1


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-01-24
      • 1970-01-01
      • 2017-02-25
      • 2020-06-06
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多