Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 number of results, so that I can show link to last page of results, and print things such as results 200 to 250 of xxx?

like image 924
flybywire Avatar asked Oct 21 '09 11:10

flybywire


People also ask

Which two methods from the query interface can be used to paginate results of a query?

When you execute a CriteriaQuery, you instantiate the same Query or TypedQuery interfaces as you use for a JPQL query. Because of that, you can use the already explained setFirstResult and setMaxResult methods to add pagination to your CriteriaQuery.

What is Hibernate criteria?

Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.


3 Answers

You can use Query.setMaxResults(int results) and Query.setFirstResult(int offset).

Editing too: There's no way to know how many results you'll get. So, first you must query with "select count(*)...". A little ugly, IMHO.

like image 143
sinuhepop Avatar answered Oct 26 '22 18:10

sinuhepop


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;
like image 8
non sequitor Avatar answered Oct 26 '22 17:10

non sequitor


you could perform two queries - a count(*) type query, which should be cheap if you are not joining too many tables together, and a second query that has the limits set. Then you know how many items exists but only grab the ones being viewed.

like image 2
Chii Avatar answered Oct 26 '22 18:10

Chii