简体   繁体   English

在Hibernate中编写SQL查询

[英]Writing sql query in hibernate

I have a sql query: 我有一个SQL查询:

     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_. 休眠状态:从Test_CPView this_中选择this_.pName作为y0_,this_.kNum作为y1_,count(与this_.agentG区别)作为y2_,其中(lower(this_.pName +'〜'+ this_.kNum)像?或lower(this_。 pName +'〜'+ this_。kNum)像?或更低(this_。pName +'〜'+ this_。kNum)像?或更低的(this_。pName +'〜'+ this_。kNum)像?) .pName,this_。 kNum 数量

and the return results are null. 并且返回结果为空。 How can I convert the above sql query into hibernate? 如何将上述sql查询转换为休眠状态?

Session.createCriteria from Docs 来自文档的Session.createCriteria

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM