[英]Hibernate noob: criteria to fetch not mapped relationship
我有两个多对多关系的类,但只有一个有另一个列表。
@Entity
public class Product{
@ManyToMany
List<Category> categories;
//...
}
@Entity
public class Category{
//...
}
我想使用Criteria查找与Category相关的所有产品,但以下内容不起作用。
import static java.util.Collections.singletonList;
List<Product> getProductsByCategory(Category category){
List<Product> results = getCurrentSession()
.createCriteria(Product.class)
.add(Restrictions.in("categories", singletonList(category)))
.list();
if (results == null || results.size() <= 0)
throw new EntityNotFoundException(category + "is empty");
return results;
}
当然,如果将Product映射到Category,那将非常简单,但肯定Hibernate让你在没有它的情况下进行这样的查询。
编辑:
它返回Oracle错误
Caused by: java.sql.SQLException: Missing IN or OUT parameter at index:: 1
谢谢你的帮助!
Criteria c = session.createCriteria(Product.class, "product");
c.createAlias("product.categories", "category");
c.add(Restrictions.eq("category.id", category.getId());
List<Product> results = c.list();
注意:结果列表永远不会为空。 它的大小永远不会<0。如果该类别没有任何产品,则返回空列表是正确的。 在这种情况下我不会抛出异常。
List<Product> results = getCurrentSession().createCriteria(Product.class)
.createCriteria("categories")
.add(Restrictions.in("id", uniqueIds(categories)))
.list();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.