JPA中一对多的子查询过滤器总和
Subquery filter sum with one to many in JPA
我有 2 个实体:
@Entity
class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Contract> contracts= new HashSet<>();
}
和
@Entity
class Contract {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Integer numberOfClaims;
}
现在我想构建一个 javax.persistence.criteria.Predicate
来查找 numberOfClaims
大于 x 的所有订单。
尝试:
select o from Order o where
(select sum(c.numberOfClaims) from o.contracts c) > x
请参阅以下 cmobilecom-jpa 开发人员指南中的一些相关子查询示例:
https://cmobilecom.com/docs/jpa/latest/devguide/index.html
使用条件API:
(参考“子查询”一章的“关联到根”部分)
CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
Root<Order> root = criteriaQuery.from(Order.class);
criteriaQuery.select(root);
criteriaQuery.distinct(true);
// Subquery: correlate the root of parent query
Subquery<Integer> subquery = criteriaQuery.subquery(Integer.class);
Root<Order> subqueryRoot = subquery.correlate(root);
Join<Order, Contract> contracts = subqueryRoot.join("contracts");
subquery.select(criteriaBuilder.sum(contracts.get("numberOfClaims")));
Predicate restriction = criteriaBuilder.greaterThan(subquery, x);
criteriaQuery.where(restriction);
我有 2 个实体:
@Entity
class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Contract> contracts= new HashSet<>();
}
和
@Entity
class Contract {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Integer numberOfClaims;
}
现在我想构建一个 javax.persistence.criteria.Predicate
来查找 numberOfClaims
大于 x 的所有订单。
尝试:
select o from Order o where
(select sum(c.numberOfClaims) from o.contracts c) > x
请参阅以下 cmobilecom-jpa 开发人员指南中的一些相关子查询示例:
https://cmobilecom.com/docs/jpa/latest/devguide/index.html
使用条件API:
(参考“子查询”一章的“关联到根”部分)
CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class);
Root<Order> root = criteriaQuery.from(Order.class);
criteriaQuery.select(root);
criteriaQuery.distinct(true);
// Subquery: correlate the root of parent query
Subquery<Integer> subquery = criteriaQuery.subquery(Integer.class);
Root<Order> subqueryRoot = subquery.correlate(root);
Join<Order, Contract> contracts = subqueryRoot.join("contracts");
subquery.select(criteriaBuilder.sum(contracts.get("numberOfClaims")));
Predicate restriction = criteriaBuilder.greaterThan(subquery, x);
criteriaQuery.where(restriction);