2014-11-20 134 views
0

如何使用Hibernate的分离标准解决此查询?对我来说最难的部分是将and u1.abrechnungsDatum is null纳入子选择。 我想这样的查询:休眠DetachedCriteria子查询中带有和子句的查询

select * 
from 
    patient as p 
where 
    p.krankenstand = ? 
and 
    ? < (select count(*) from ueberweisung u1 where p.id = u1.patient_id 
     and u1.abrechnungsDatum is null) 

我有这个

DetachedCriteria dc = DetachedCriteria.forClass(Patient.class, "patient"); 
dc.add(Restrictions.eq("krankenstand", true)); 

DetachedCriteria nab = dc.createCriteria("ueberweisungs", "nab"); 
nab.add(Restrictions.isNull("nab.abrechnungsDatum")); 
dc.add(Restrictions.sizeGt("ueberweisungs", 0)); 

这给了我下面的SQL语句试过

select 
    * 
from 
    patient this_ 
inner join 
    ueberweisung nab1_ 
     on this_.id=nab1_.patient_id 
where 
    this_.krankenstand=? 
    and nab1_.abrechnungsDatum is null 
    and ? < (
     select 
      count(*) 
     from 
      ueberweisung 
     where 
      this_.id=patient_id 
    ) 

正如你所看到的,和 - 字段abrechnungsDatum不适用于子选择。我怎样才能做到这一点呢?

回答

0

试试这个:

DetachedCriteria dc = DetachedCriteria.forClass(Patient.class, "patient"); 
dc.add(Restrictions.eq("krankenstand", true)); 

DetachedCriteria subquery = DetachedCriteria.forClass(Ueberweisung.class); 
subquery.add(Restrictions.isNull("abrechnungsDatum")); 

dc.add(Subqueries.ltAll(0, subquery)); 
+0

谢谢您的回答,但你的suggesetion抛出一个'NullPointerException'。我必须设置一个投影,所以我尝试了这种方式: (参见上面的“编辑A”) 无论如何,这也不会给我我想要的结果,因为那样我就失去了连接'p.id =子查询中的u1.patient_id'。结果SQL显示在答案的“编辑B”中。 – Tarator 2014-11-21 11:41:51

+0

它是否适用于您更新的查询? – 2014-11-21 11:44:11

+0

不,不幸的是,这不是我想要的...请参阅上面的编辑...问题是,我没有将主要查询的“患者”加入连接。 – Tarator 2014-11-21 11:47:46