0

我在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 

这个查询很好并且工作正常,但我想使用休眠的条件查询代替上面的 SQL 查询,因为我在我的应用程序中使用休眠。我在添加条件时遇到问题,例如planId=(SELECT MAX(p.planId) FROM plan p WHERE c.clientId=p.clientId GROUP BY p.clientId)如何在休眠条件中编写上述 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 查询很好,所以我想要使用休眠条件的相同查询。

4

0 回答 0