Criteria Query and pagination params « Intelligrape Groovy & Grails Blogs

Criteria Query and pagination params

Posted by Bhagwat Kumar

I have been using the following code to get paginated result and the total number of results returned irrespective of the pagination params.

 def result=SampleDomain.createCriteria().list(){
// multiple restrictions
   maxResults(params.max)
   firstResult(params.offset)
} // Return type is ArrayList
 
Integer  totalResult=SampleDomain.createCriteria().count(){
// multiple restrictions
// maxResults(params.max)
// firstResult(params.offset)
}

Clearly duplicating the same closure except for the pagination restrictions was not a good solution.

After a little googling and reading mailing lists I got the solution. Passing pagination params to createCriteria.list() returns result of type PagedResultList which provides many useful methods. The getTotalCount() method of PagedResultList class returns the actual number of results returned irrespective of the pagination restrictions(maxResults and firstResult). Also the result contains only those records fulfiling maxResults and firstResult restrictions.

def result=SampleDomain.createCriteria().list(max:params.max, offset:params.offset){
// multiple/complex restrictions
   maxResults(params.max)
   firstResult(params.offset)
} // Return type is PagedResultList

Thanks to all the active users of Grails mailing list.

Here are few useful links:
http://www.pubbs.net/grails/200912/2269
http://www.grails.org/doc/1.0.x/api/grails/orm/PagedResultList.html
http://jira.codehaus.org/browse/GRAILS-2672

Bhagwat Kumar
bhagwat(at)intelligrape(dot)com

  • Share/Bookmark
This entry was posted on July 14th, 2010 at 10:48 pm and is filed under Grails . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

4 Responses to “Criteria Query and pagination params”

  1. Raja_M says:

    The information here is valuable…but could you go one step further with your description?

    Having got the PagedResultSet…how do you get proper pagination?

    I can render with the “list” view using the PagedResultSet – which displays the first page (and the correct number of pages). Clicking on any page number – however causes the result set to disappear.

    Does the PagedResultSet need to be “saved” – How? Or, do we need to re-execute the query for every page number?

    Either a complete code sample or more complete description would be helpful.

    Thanks

  2. Hi,
    You need to re-execute the query for every page number.

  3. Un blog interesante, me ha gustado mucho. Te sigo habitualmente

  4. shahbaz says:

    User params in g:pagination will help.e.g,

Leave a Reply