Criteria Query and pagination params

14 / Jul / 2010 by Bhagwat Kumar 4 comments

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:

Bhagwat Kumar
bhagwat(at)intelligrape(dot)com

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. Raja_M

    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

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *