Java Hibernate 条件返回页和行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18484988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:03:59  来源:igfitidea点击:

Hibernate criteria return page and rowcount

javahibernate

提问by dinesh

Using Hibernate Criteria i am trying to achieve pagination but the problem is that for every page fetch i have to make two db calls one for results and another for total records count. Is there any efficient way so that in a single db call i can get both the data or i can reduce db calls.

使用 Hibernate Criteria 我试图实现分页,但问题是对于每个页面提取,我必须进行两次 db 调用,一个是结果,另一个是总记录数。有没有什么有效的方法,以便在单个 db 调用中我可以获得两个数据,或者我可以减少 db 调用。

 Criteria criteria=session.createCriteria(Student.class);
 criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
 criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED));
 criteria.setMaxResults(10);
 criteria.setFirstResult((paginate.getStartIndex()-1)*10);

 criteria.setProjection(Projections.rowCount());
//here i need to fetch total row count and records

采纳答案by Prabhakaran Ramaswamy

Yes you need the separate query to get the total result count.

是的,您需要单独的查询来获取总结果计数。

    Query aCountQuery  = session.createQuery("select count(s.id) from Student s 
           where s.enquiryStatus != :enquiryStatus");
           aCountQuery.setParameter("enquiryStatus", ENQUIRY.JOINED);
    Long resultCount = (Long)aCountQuery.uniqueResult();

or

或者

   Criteria criteria=session.createCriteria(Student.class);
        criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED));
        criteria.setProjection(Projections.rowCount())
   Long resultCount = (Long)criteria.uniqueResult();

Update

更新

Now you can use same Criteria for results with pagination and result count

现在您可以使用相同的标准来获得分页和结果计数的结果

  Criteria criteria=session.createCriteria(Student.class);
     criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
     criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED));
     criteria.setMaxResults(10);
     criteria.setFirstResult((paginate.getStartIndex()-1)*10);
     List<Student> students = criteria.list();

    criteria.setProjection(null);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    Long resultCount = (Long)criteria.uniqueResult();

回答by Suresh Atta

As far As I know there is no direct method to do so.As simple as you can do is write a small hql query(my choice) ,Along with your main criteria.

据我所知,没有直接的方法可以做到这一点。你能做的最简单的事情就是写一个小hql query(我的选择),连同你的主要criteria.

Number count = (Number) session.createQuery(
    "select count(s.id) from Student s").uniqueResult();