views:

473

answers:

2

Hi, I need to add paginator for my Hibernate application. I applied it to some of my database operations which I perform using Criteria by setting Projection.count().This is working fine. But when I use hql to query, I can't seem to get and efficient method to get the result count. If I do query.list().size() it takes lot of time and I think hibernate does load all the objects in memory.

Can anyone please suggest an efficient method to retrieve the result count when using hql?

A: 

I've done similar things in the past. If you want to get a total count of records for the paginator, then I'd suggest a separate query that you do first. This query should just do a count and return the total.

As you suspect, in order to count your records on your main query, hibernate does have to load up all the records, although it will do it's best to not load all the data for each record. But still this takes time.

If you can get away with it, because even a count query can take time if your where clauses are inefficient, just check that you got a full page of records back, and put up an indicator of some sort to show that there could be more results on the next page. That's the fastest method because you are only queries for each page as you need it.

Derek Clarkson
Hey, thanks for the response.The thing that you suggested that I can set some type of indicator to show that ther might be more records..the problem with that is if my pageSize is 10, and suppose that there are 100 records, then for the 10th page I would get 10 results and I might set up indicator stating there might be more records. The thing is we need to send in the results to UI via web services and in this case the last call with no results may prove too expensive to us...
KCore
Ok, another trick I have used in the past to work around this is that rather than bring back 10 results each time, I request 11. I still display 10, but the presence of the 11th result is used to indicate that a "more results" link can be added, safely knowing there is more results. Other than that, you really have to look at an initial count query to find out how many results there are before you start requesting pages rows. Counts can be very fast if you indexes are good because the database (not hibernate) does the work.
Derek Clarkson
This trick is cool....I can use this.The issue with initial count is my queries will be too complex and and each time to build a corresponding count query (simple but) will be a overhead for me, as there are some 3-4 layers (calls) involved in between from where I build my query and where I actually execute my query. I dont want to increase my stack.. :)
KCore
A: 

You'll have to use another query and Query#iterate(). See section 14.16. Tips & Tricks:

You can count the number of query results without returning them:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()
Pascal Thivent