我正在使用JPA并尝试选择给定Product
个父母(List
)的所有childentities(Category
)。关系是Category OneToMany Product
。我想将其保留为一个查询,而不是像Predicate
那样创建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
答案 0 :(得分:0)
您可以使用类别ID而不是类别对象(因为错误状态:不支持对象比较):
(假设您的类别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();
}