简体   繁体   English

Java JPA:选择“列表中的ATTRIBUTE在列表中>”

[英]Java JPA: Select 'ATTRIBUTE is in List<>'

I am using JPA and trying to select all childentities ( Product ) of a given List of parents ( Category ). 我正在使用JPA并尝试选择给定父母ListCategory )的所有子项( Product )。 The relationship is Category OneToMany Product . 关系是Category OneToMany Product I would like to keep it down to one query and not create a Predicate like product.get("category") == category.get(0) || product.get("category") == category.get(1) || ... 我想将其简化为一个查询,而不创建像product.get("category") == category.get(0) || product.get("category") == category.get(1) || ...这样的Predicate product.get("category") == category.get(0) || product.get("category") == category.get(1) || ... product.get("category") == category.get(0) || product.get("category") == category.get(1) || ... . product.get("category") == category.get(0) || product.get("category") == category.get(1) || ...

I have tried the following bit of code, but this does not seem to work (as seen in the stack at the bottom). 我已经尝试了以下代码,但这似乎不起作用(如底部的堆栈所示)。 Does anyone have a suggestion as how to accomplish this? 有没有人建议如何做到这一点?

Code

public List<Product> findProductsBy(List<Category> categories) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Product> query = cb.createQuery(Product.class);
    Root product = query.from(Product.class);
    Predicate predicateCategory = product.get("category").in(categories);

    query.select(product).where(predicateCategory);
    return em.createQuery(query).getResultList();
}

Stack

WARNING: Local Exception Stack: 
Exception [EclipseLink-6075] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.QueryException
Exception Description: Object comparisons can only use the equal() or notEqual() operators.  Other comparisons must be done through query keys or direct attribute level comparisons. 
Expression: [
Relation operator [ IN ]
   Query Key category
      Base (...).Product

What you can do is using the category id instead of the category object (as the error state: object comparison is not supported ): 您可以使用类别ID代替类别对象(因为错误状态: 不支持对象比较 ):

(Assuming your category id is a Long , you can do the following.) (假设您的类别ID是Long ,则可以执行以下操作。)

public List<Product> findProductsBy(List<Category> categories) {
    List<Long> categoryIds = new ArrayList<Long>();
    for(Category category:categories){
        categoryIds.add(category.getId());
    }
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Product> query = cb.createQuery(Product.class);
    Root product = query.from(Product.class);
    Predicate predicateCategory = product.get("categoryId").in(categoryIds);

    query.select(product).where(predicateCategory);
    return em.createQuery(query).getResultList();

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM