Search code examples
grailsgrails-ormgrails-domain-class

how to create custom queries in grails domain


Is there a way to create a query in a grails domain that always returns the records that have a specific criteria?

For example:

Class Person {

  String firstname
  String lastname
}

Now instead of saying Person.findByFirstname("Bart") all over the codebase is there anything I can do inside the Person domain class so that I can simply say something like Person.bart


Solution

  • The namedQueries support available within Grails/GORM should meet this need: http://grails.org/doc/latest/ref/Domain%20Classes/namedQueries.html

       static namedQueries = {
           firstNameBart {
               eq 'firstname', 'Bart'
           }
       }
    

    Then used in this way:

    def barts = Person.firstNameBart.list()