我具有以下关系,我需要吸引至少购买了一次的消费者(作为子查询,因为这是较大查询的一部分)。
@Entity
@Table(name = "consumers")
public class Consumer extends User {
@JsonIgnore
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "consumer_id")
private List<Purchase> purchases;
}
和查询
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Consumer> criteriaQuery = criteriaBuilder.createQuery(Consumer.class);
Root<Consumer> root = criteriaQuery.from(Consumer.class);`
Join<Consumer, Purchase> purchases = root.join(Consumer_.purchases, JoinType.LEFT);
sub.select(criteriaBuilder.count(purchases.get(Purchase_.id)));
sub.where(criteriaBuilder.equal(root.get(Consumer_.id), purchases.get(Purchase_.consumer).get(Consumer_.id)));
predicates.add(criteriaBuilder.greaterThanOrEqualTo(sub, 0L));