Get total records count with GORM criteria

ava-s-dmitriy-drenkalyuk

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:

def items = Item.createCriteria().list(max: 10, offset: 0) {
    /* criteria query */
}
def totalRecords = items.totalCountCode language: PHP (php)

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.

ava-s-dmitriy-drenkalyuk
DevOps / Senior Software Engineer