views:

263

answers:

1

Hello,

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?

A: 

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());

candiru
So I need to make two queries, one for the row count, the other for the actual data???
mlaverd
If you really want to have exact results, then yes. But before you start to worry about performance, check the documentation of your underlying database, because it might be able to do it very effectively.
candiru