hibernatepagination

Hibernate: page results AND know the result size


I'm doing a directory listing using Hibernate and, to avoid having tons of data every query, I'm using:

Criteria paging = sess.createCriteria(Principal.class);
paging.setFirstResult((int) resultSetStart);
paging.setMaxResults(resultSetSize);
...
List<Principal> principals = paging.list();

Now, this works fine: I guess exactly resultSetSize results. However, I want to do something like Google has, 'showing page X out of Y'.

How can I know the total number of entries? Or the total number of pages?


Solution

  • There is really no way to get the number of all results without invoking some COUNT() query. So either you have to do some approximation (as Google does), or you can just count the number of total entities before you execute your query by using:

    paging.setProjection(Projections.rowCount());