Search code examples
grails

Find max value in table column


I am creating a version control domain class in Grails:

class VersionControl {

    Date dateCreated
    Long versionNumber

    Long getLatestVersionNumber() {
        //return largest versionNumber
    }

}

I would like to add a query to get the largest version number stored:

Long getLatestVersionNumber()

In SQL this query would look more or less as follows:

SELECT TOP 1 MAX(versionNumber) FROM VersionControl

The function MUST return the value as a long.

What is the correct way to do this in Grails?


Solution

  • You can use GORM criteria, querying with projections:

    VersionControl.createCriteria().get {
        projections {
            max "versionNumber"
        }
    } as Long