这个问题是关于使用Hibernate Criteria
来执行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
答案 0 :(得分:3)
尝试使用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();