【问题标题】:How to Count the rows in Hibernate Query Language?如何计算 Hibernate 查询语言中的行数?
【发布时间】:2012-01-30 13:30:45
【问题描述】:

我试图只获取返回的行数,而不是表中的所有结果。

我看到可以这样做:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()

但是当试图以整数格式存储这个查询时(它说不能从Query to Integer转换)

我正在使用动态查询,其中值将在查询下方提及

theQuery = "select count(*) from THM as thm " + 
                "join thm.TMC as tmc " +
                "join tmc.TIMCC as timcc " +
                "where thm.Qid = :Qid and thm.Cv = :Cv and timcc.Did = :Did and timcc.Cv= :Cv";

Query query = session.createQuery(theQuery);
query.setInteger("Qid", Integer.parseInt(Qid));
query.setInteger("Did", Did);
query.setInteger("Cv",cV);

现在,我如何在不使用 list.size 而是直接从查询中获取通过在变量中使用 Hibernate 查询返回的所有行的计数?

【问题讨论】:

    标签: java database hibernate hql


    【解决方案1】:

    您是否尝试过 query.uniqueResult(); ?由于您的 Select count(*) 只会给您一个数字,因此您应该可以使用 int count = (Integer)query.uniqueResult(); 之类的方法检索它;

    要根据标准进行计数,您可以这样做:

    Criteria criteria = currentSession().createCriteria(type);
    criteria.setProjection(Projections.rowCount());
    criteria.uniqueResult();
    

    我现在正在使用标准,所以我确信它有效。我在这里的网站上看到了 uniqueResult() 解决方案:http://www.jroller.com/RickHigh/entry/hibernate_pagination_jsf_datagrid_prototype1

    【讨论】:

    • query.uniqueResult();工作得很好, .iterate().next() ).intValue()
    • 如果我的查询不是 Select count(*) 而是像“来自 THM”一样开始
    • SharedSessionContract 类型的 createCriteria(String) 方法已弃用。
    【解决方案2】:

    你可以这样做

    long count = (long)session.createQuery("SELECT COUNT(e) FROM Employees e").getSingleResult();
    

    【讨论】:

      【解决方案3】:

      试试看。

      Long count = ((Long) session.createQuery("select count(*) from Book").uniqueResult());
      Integer totalBooks = count.intValue();
      

      【讨论】:

        【解决方案4】:

        为我工作

        int list=(int) 
        sessionFactory.getCurrentSession().createSQLQuery("select count(*) as count from 
                                 Book").addScalar("count",IntegerType.INSTANCE).uniqueResult();
        

        【讨论】:

          猜你喜欢
          • 2019-10-31
          • 1970-01-01
          • 2013-09-03
          • 2011-03-02
          • 1970-01-01
          • 2014-09-08
          • 2021-02-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多