Hibernate DetachedCriteria在子选择中使用和子句查询

时间:2014-11-20 19:49:59

标签: java hibernate detachedcriteria

如何使用Hibernate的分离标准解决此查询?对我来说最困难的部分是将and u1.abrechnungsDatum is null带入子选择。 我想要一个像这样的查询:

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的and子句不在子选择内。我怎样才能实现这个目标?

1 个答案:

答案 0 :(得分: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));