使用条件而不是本机查询

时间:2016-05-19 09:53:42

标签: hibernate

我有下面的hibernate本机查询,如下图所示的想法是不使用本机查询并切换到hibernate条件api

 <![CDATA[select count(iilnmp.INV_LINE_NOTE_ID) from IOA_INV_LINE_NOTE_MAP iilnmp , 
                                                    IOA_INVOICE_LINE_NOTES iiln , IOA_INVOICE_LINE iil
                                                   where   iilnmp.INV_LINE_NOTE_ID = iiln.ID and iiln.INLI_ID =iil.id and iil.ID = ?]]>

我从一个如下所示的方法调用现在我的查询是,我可以使用标准来实现相同的结果而不是原生查询

 public int findAttachementsCount(long id)
    {   
        Query query = session.getNamedQuery("attachmentQuery");
        query.setParameter(0, id);
        int attachCount = query.list().size(); 
        return attachCount;
    }   

请各位提出建议。请有人请优先考虑这个.. !!

2 个答案:

答案 0 :(得分:0)

public int findAttachementsCount(long id)
    Criteria c = session.createCriteria(YourClass.class, "alias");
    c.createAlias("fieldOfyoursecondClass.role", "role"); // inner join by default
    c.setProjection(Projections.rowCount())
    c.add(Restrictions.eq("alias.id", id));
return ((Long)c.uniqueResult()).getIntValue();

Original question - Joins | Original question - Source - Count

答案 1 :(得分:0)

Criteria c = session.createCriteria(IOA_INV_LINE_NOTE_MAP.class, "iilnmp");
c.createAlias("iilnmp.INV_LINE_NOTE_ID", "iiln");
c.createAlias("iiln.INLI_ID", "iil");

// restrictions
c.add(Restrictions.eq("iil.ID", id));

// projections
c.setProjections(Projections.count("iilnmp.INV_LINE_NOTE_ID"));

// run query
c.uniqueResult();