I use MySQL, and the scroll solution is a very bad idea on MySQL, I found that it was very slow. There is a much cleaner and more elegant approach, use a projection:
Code:
criteria.setProjection(Projections.rowCount());
Integer count = (Integer) criteria.uniqueResult();
itemCount = count.intValue();
criteria.setProjection(null);
criteria.setResultTransformer(Criteria.ROOT_ENTITY);
Notice the setProjection(null) and setResultTransformer which set the criteria query back to how it was.
(I do this before I set the max results).
This of course only works if you use the Criteria API, but I find that this API is quite useful for the typical cases where I need pagination anyway.[/code]
When I tested this solution against the scrolling solution (on mysql, which doesn't have cursors), I found that the scroll solution used the same amount of time as when I simply called list(), i.e. queried for all matching projects. The rowCount solution given here simply executes a COUNT(*) so it's much faster.