我在sql中编写了一个查询,就像......
SELECT c.clientfirstname,
c.clientlastname,
c.clientage,
c.status,
Sum(i.annualamount) AS amount,
p.planname,
c.clientid
FROM client c,
income i,
plan p
WHERE c.clientid = i.clientid
AND planid = (SELECT Max(p.planid)
FROM plan p
WHERE c.clientid = p.clientid
GROUP BY p.clientid)
AND ( c.clientfirstname LIKE 'rahul' )
GROUP BY i.clientid
这个查询很好并且工作正常,但我想使用hibernate的条件查询代替上面的SQL查询,因为我在我的应用程序中使用hibernate。
我在添加planId=(SELECT MAX(p.planId) FROM plan p WHERE c.clientId=p.clientId GROUP BY p.clientId)
之类的条件时遇到了问题,所以如何在hibernate条件中编写上面的sql查询。我试过这个查询
DetachedCriteria dc = DetachedCriteria.forClass(Client.class);
dc.createAlias("plans", "pla");
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max("pla.planId"));
proj.add(Projections.groupProperty("clientId"));
dc.setProjection(proj);
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Client.class);
criteria.createAlias("incoms", "inco");
criteria.createAlias("plans", "plan");
Criterion firstname = Restrictions.like("clientFirstName", searchValue+"%");
criteria.setProjection(
Projections.projectionList()
.add(Projections.property("clientFirstName"))
.add(Projections.property("clientLastName"))
.add(Projections.property("clientAge"))
.add(Projections.property("status"))
.add(Projections.sum("inco.annualAmount"))
.add(Projections.property("plan.planName"))
.add(Projections.groupProperty("clientId"))
);
criteria.add(Subqueries.propertyEq("plan.planId", dc));
Disjunction disjunction = Restrictions.disjunction();
disjunction.add(firstname);
criteria.add(disjunction);
return criteria.list();
}
但我得到这样的错误......
Hibernate:
select this_.clientFirstName as y0_, this_.clientLastName as y1_,
this_.clientAge as y2_, this_.status as y3_, sum(inco1_.annualAmount) as y4_,
plan2_.planName as y5_, this_.clientId as y6_
from Client this_ inner join Income inco1_ on this_.clientId=inco1_.clientId
inner join Plan plan2_ on this_.clientId=plan2_.clientId
where plan2_.planId =
(select max(pla1_.planId) as y0_, this_.clientId as y1_
from Client this_ inner join Plan pla1_ on this_.clientId=pla1_.clientId
group by this_.clientId
)
and (this_.clientFirstName like ?
or this_.clientLastName like ?
or this_.clientPhoneNo like ?
or this_.clientEmail like ?)
group by this_.clientId
错误:无法执行查询
有三个表收入计划和客户,客户ID是计划和收入表中的外键,而在计划表中有一个客户ID可用的许多计划名称,我想从计划中通过clientId获取最后一个计划组表...
我的上面(在上面)SQL查询很好所以我想要使用hibernate标准的相同查询。