0
votes

I have a sql query:

     select COUNT (distinct agentG) as count from Test_CPView where kNum = ‘test k1’ and pName = ‘test p1’

I'm trying to write into criteria query but it hasn't worked for me:

    statelessSession = sessionFactory.openStatelessSession();
    Criteria crit = statelessSession.createCriteria(APRecord.class, "apr");

    ProjectionList projList = Projections.projectionList();

        projList.add(Projections.groupProperty("pName"));
        projList.add(Projections.groupProperty("kNum"));
        projList.add(Projections.countDistinct("agentG"));
        crit.setProjection(projList);

This produces:

Hibernate: select this_.pName as y0_, this_.kNum as y1_, count(distinct this_.agentG) as y2_ from Test_CPView this_ where (lower(this_. pName + '~' + this_. kNum) like ? or lower(this_. pName + '~' + this_. kNum) like ? or lower(this_. pName + '~' + this_. kNum) like ? or lower(this_. pName + '~' + this_. kNum) like ?) group by this_.pName, this_. kNum

and the return results are null. How can I convert the above sql query into hibernate?

3

3 Answers

0
votes

Session.createCriteria from Docs

You have not added Restrictions

    statelessSession = sessionFactory.openStatelessSession();
        Criteria crit = statelessSession.createCriteria(APRecord.class, "apr");
    crit .add(Restrictions.eq("kNum", "test k1"));
    crit .add(Restrictions.eq("pName ", "test k1"));
    crit.setProjection(Projections.countDistinct("agentG"));
    Integer count = crit.uniqueResult();
0
votes
statelessSession = sessionFactory.openStatelessSession();
Criteria crit = statelessSession.createCriteria(APRecord.class, "apr");
crit.add(Expression.eq("kNum","test k1"));
crit.add(Expression.eq("pName","test p1"));
crit.setProjection(Projections.countDistinct("agentG"));
0
votes
Query query = session.createQuery("count(agentG) from APRecord where kNum = :kNum and pName = :pName");
query.setParameter("kNum", "test k1");
query.setParameter("pName", "test p1");
return (Integer) query.uniqueResult();