0

我正在使用 JPA 并尝试选择Product给定List父母( )的所有子实体( Category)。关系是Category OneToMany Product。我想将其保留为一个查询,而不是创建一个Predicatelike product.get("category") == category.get(0) || product.get("category") == category.get(1) || ...

我已经尝试了以下代码,但这似乎不起作用(如底部的堆栈所示)。有没有人建议如何做到这一点?

代码

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();
}

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
4

1 回答 1

0

您可以做的是使用类别 id 而不是类别对象(作为错误状态:不支持对象比较):

(假设您的类别 id 是 a 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();

}

于 2013-02-01T14:31:56.003 回答