我的MySQL查询是:
SELECT
c.first_name,
c.middle_name,
c.last_name,
s.ticker,
COUNT(s.ticker),
SUM(t.cumulative_qty),
SUM(cumulative_balance)
FROM client_master c, security s, transaction_master t
WHERE c.id = t. client_master_id AND s.id = t.security_id AND t.client_master_id = 4
GROUP BY t.security_id;
此查询返回精确结果。我想编写具有匹配结果的Hibernate Criteria。这就是我试过的:
Criteria criteria = createEntityCriteria(TransactionDetails.class, "tr")
.createAlias("tr.client", "cl")
.createAlias("tr.security", "se")
.add(Restrictions.eq("cl.id", clientId))
.setProjection(Projections.sum("tr.cumulativeQty"))
.setProjection(Projections.groupProperty("tr.securityId"));
return criteria.list();
但此标准仅返回List
tr.securityId
。我想要所有的行。我哪里错了?
答案 0 :(得分:5)
您不能多次执行setProjection()
次。您需要先创建ProjectionList
,然后设置每个投影。您还需要通过在Projections.property()
中指定它们来告诉您在结果集中需要哪些字段。
试试这个:
ProjectionList projList = Projections.projectionList();
projList.add(Projections.sum("tr.cumulativeQty"));
projList.add(Projections.groupProperty("tr.securityId"));
projList.add(Projections.property("firstName"));
projList.add(Projections.property("lastName"));
//add other fields you need in the projection list
Criteria criteria = createEntityCriteria(TransactionDetails.class, "tr")
.createAlias("tr.client", "cl")
.createAlias("tr.security", "se")
.add(Restrictions.eq("cl.id", clientId))
.setProjection(projList);
答案 1 :(得分:0)
此外,您可以使用多个投影内联标准。如下所示。
Criteria criteria = createEntityCriteria(SomeClass.class)
.createAlias(...some elias...)
.add(Restrictions..... etc)
.setProjection(
Projections.projectionList()
.add(Projections.groupProperty("someProp1"))
.add(Projections.property("someProp2"))
.add(Projections.sum("someProp3"))
);