-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: Selecting result count with Criteria.
PostPosted: Wed Mar 11, 2009 2:32 am 
Beginner
Beginner

Joined: Sun Jan 11, 2009 2:47 pm
Posts: 21
I'm using Criteria with setFirstResult/setMaxResults to retrieve a subset of the result set (for paging results on a web page). However, I also want to know the total number of results in the result set. What's the most efficient way to do this when using Criteria?

I could run two queries, one with the subset, and one with the full set, and use Criteria.list().size() to get the total size of the entire set, but then that just retrieves the entire result set which is pretty slow and isn't what I want -- it defeats the purpose of paging the results to being with.

Another thing I thought of was using Criteria to build a query like "select count(*) from ...", but I don't know how to do this.

So the question is, what's the best way to get the size of the entire result set through Criteria when I'm using setFirstResult/setMaxResults to only retrieve a subset?

Thanks!


Top
 Profile  
 
 Post subject: Re: Selecting result count with Criteria.
PostPosted: Wed Mar 11, 2009 4:10 am 
Senior
Senior

Joined: Wed Sep 19, 2007 9:31 pm
Posts: 191
Location: Khuntien (Indonesia)
I think you need to retrieve twice. First is the data. Second is the number of records.

To retrieve the total records, you can use
Code:
Criteria criteria = session.createCriteria(SomeClass.class);
criteria.setProjection(Projections.rowCount());
List<Number> list = criteria.list();


Top
 Profile  
 
 Post subject:
PostPosted: Wed Mar 11, 2009 4:12 am 
Beginner
Beginner

Joined: Sun Jan 11, 2009 2:47 pm
Posts: 21
Ah thanks, works great. Projections are exactly what I was looking for.

Thanks! :)


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.