Implementing result paging in hibernate (getting total number of rows)

前端 未结 5 1578
谎友^
谎友^ 2020-12-09 19:44

How do I implement paging in Hibernate? The Query objects has methods called setMaxResults and setFirstResult which are certainly helpful. But where can I get the total numb

5条回答
  •  無奈伤痛
    2020-12-09 20:18

    You must do a separate query to get the max results...and in the case where between time A of the first time the client issues a paging request to time B when another request is issued, if new records are added or some records now fit the criteria then you have to query the max again to reflect such. I usually do this in HQL like this

    Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();
    

    for Criteria queries I usually push my data into a DTO like this

    ScrollableResults scrollable = criteria.scroll(ScrollMode.SCROLL_INSENSITIVE);
    if(scrollable.last()){//returns true if there is a resultset
        genericDTO.setTotalCount(scrollable.getRowNumber() + 1);
        criteria.setFirstResult(command.getStart())
                .setMaxResults(command.getLimit());
        genericDTO.setLineItems(Collections.unmodifiableList(criteria.list()));
    }
    scrollable.close();
    return genericDTO;
    

提交回复
热议问题