2012-12-21 110 views
2

這個問題是關於使用休眠Criteriagroup by
這裏是我的SQL:休眠條件groupProperty

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

,但我得到了以下錯誤:不是個createCriteria的

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

回答

3

嘗試createAlias。它會產生一個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(); 
+0

@ user1774599。不要忘記標記答案,如果它的工作。 –

+0

謝謝,它像一個魅力。 – user1774599