在hibernate中编写sql查询

时间:2015-08-10 15:27:46

标签: java sql hibernate hibernate-criteria

我有一个SQL查询:

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

我试图写入条件查询,但它对我没用:

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

这会产生:

Hibernate:选择this_.pName为y0_,this_.kNum为y1_,count(distinct this_.agentG)为y2_,来自Test_CPView this_ where(lower(this_。pName +'〜' + this_。 kNum)喜欢?或更低(this_。pName +'〜' + this_。kNum)喜欢?或更低(this_。pName +'〜' + this_。kNum)喜欢?或更低(this_。pName +'〜' + this_。kNum)喜欢?)group by this_.pName,this_。 KNUM

并且返回结果为null。 如何将上述sql查询转换为hibernate?

3 个答案:

答案 0 :(得分:0)

Session.createCriteria from Docs

您尚未添加限制

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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