【问题标题】:Hibernate DetachedCriteria Query with and clause in subselectHibernate DetachedCriteria 查询与子选择中的和子句
【发布时间】:2014-11-20 19:49:58
【问题描述】:

如何使用 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 子句不在子选择内。我怎样才能做到这一点?

【问题讨论】:

    标签: java hibernate detachedcriteria


    【解决方案1】:

    试试这个:

    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));
    

    【讨论】:

    • 感谢您的回答,但您的建议会引发NullPointerException。我必须设置一个投影,所以我尝试了这种方式:(参见上面的“编辑 A”)无论如何,这也没有给我想要的结果,从那时起我在子查询中失去了连接 p.id = u1.patient_id。生成的 SQL 显示在您的答案中的“编辑 B”中。
    • 不,不幸的是,这不是我想要的...请参阅上面的编辑...问题是,我失去了与主查询的 Patient 的连接。
    • 但是:我用 HQL 解决了这个问题,它的工作原理就像一目了然。所以,谢谢你的帮助。不要在这上面浪费更多时间,尽管我仍然对解决方案感兴趣(只是为了学习:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    相关资源
    最近更新 更多