Spring JPA 条件 API 查询 OneToMany 列表字段

Spring JPA Criteria API Query on OneToMany List Field

我想加载具有 JPA/Hibernate 条件 API 的特定客户的所有 CustomerRequests。

具体来说:我想加载所有存在具有特定 customerId 的 CustomerRequest2Customer 条目的 CustomerRequest。

@Entity
public class CustomerRequest {
    @Id
    private int id;
    private int priority;
    @OneToMany(mappedBy = "customerRequestId")
    private List<CustomerRequest2Customer> listCustomerRequestToCustomer; //  <- Query this field         
}

@Entity
public class CustomerRequest2Customer {
    @Id
    private int id;
    @ManyToOne
    private Customer customer; //  <- Query this field
    @ManyToOne
    private CustomerRequest customerRequest;
}

@Entity
public class Customer {
    @Id
    private int id; //  <- Query this field
    private String name;
}

我目前查询其他字段的方式:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<CustomerRequest> cq = 
cb.createQuery(CustomerRequest.class);
Root<CustomerRequest> root = cq.from(CustomerRequest.class);
cq.where(cb.equal(root.get("priority"), 1));
return entityManager.createQuery(cq).getResultList();

您必须像这样加入实体:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<CustomerRequest> cq = cb.createQuery(CustomerRequest.class);

Root<CustomerRequest> root = cq.from(CustomerRequest.class);
Join<CustomerRequest, CustomerRequest2Customer> customerRequest2Customer = root.join("listCustomerRequestToCustomer");
Join<CustomerRequest2Customer, Customer> customer = customerRequest2Customer .join("customer");

cq.where(cb.equal(customer .get("id"), 1));

return entityManager.createQuery(cq).getResultList();