'Get total records count with GORM criteria' post illustration

Get total records count with GORM criteria

avatar

Assume you have a page with pagination that displays some objects table (selected from DB with GORM criteria) in your Grails application. If you want to know total number of possible results (as if there are no pagination parameters), you can do it in this way:

1
2
3
4
def items = Item.createCriteria().list(max: 10, offset: 0) {
    /* criteria query */
}
def totalRecords = items.totalCount

I.e., if you pass at least one parameter (max, offset, sort, order) to the criteria method, it returns results as grails.orm.PagedResultList, which has the getTotalCount() method. In other cases (without pagination parameters, even if the maxResults / firstResult options are set inside the criteria query), it returns just ArrayList.

If you're looking for a developer or considering starting a new project,
we are always ready to help!