PagedResultList « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ PagedResultList ’

Criteria Query and pagination params

Posted by Bhagwat Kumar on July 14th, 2010

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
Posted in Grails