2

这个问题是关于使用 HibernateCriteria进行group by.
这是我的 SQL:

SELECT s.name, max(p.price), min(p.price)
FROM supplier s, product p
WHERE s.supplier_id = p.supplier_id
GROUP BY s.name

我尝试了以下方法:

Criteria criteria = session.createCriteria(Supplier.class); 

Criteria prodCrit = criteria.createCriteria("products"); 

ProjectionList projList = Projections.projectionList(); 
projList.add(Projections.max("price"));
projList.add(Projections.min("price")); 
projList.add(Projections.groupProperty("name"));
prodCrit.setProjection(projList);
List list = criteria.list();

但我收到以下错误:

Exception in thread "main" org.hibernate.QueryException: could not resolve property: price of: com.gtc.hibernate.query.Supplier
4

1 回答 1

4

尝试使用 createAlias 而不是 createCriteria。它将产生一个 SQL 查询。

select 
       max(p1_.price) as y0_, 
       min(p1_.price) as y1_, 
       this_.name as y2_ 
from Supplier this_ 
   inner join Product p1_ on this_.id=p1_.supplier_id 
 group by this_.name;

标准 :

Criteria criteria = session.createCriteria(Supplier.class); 
criteria.createAlias("products","p");

ProjectionList projList = Projections.projectionList(); 
projList.add(Projections.max("p.price"));
projList.add(Projections.min("p.price")); 
projList.add(Projections.groupProperty("name"));
criteria.setProjection(projList);
List list = criteria.list();
于 2012-12-21T17:10:26.473 回答