4

Is possible to call namedQuery on grails inside a controller? I know that I can call a namedQuery inside another namedQuery, but i dont want to do that. Any ideas? Thanks

User.groovy

static namedQueries = {
      filterUsers{
            eq("age", 21)
      }
}

MyController.groovy

def r = User.createCriteria().list {
     eq("id", 1)
     filterUsers() //not possible
}

or..

MyController.groovy

    //not possible too
    //Cannot invoke method createCriteria() on null object

    def r = User.filterUsers().createCriteria().list {
         eq("id", 1)           
    }
Luccas
  • 4,078
  • 6
  • 42
  • 72

1 Answers1

4

Here's an example:

Domain:

class User {

    int age
    String userName

    static namedQueries = {
        filterUsers {
            eq("age", 21)
        }
    }

    static constraints = {
    }
}

Controller:

class TestController {

    def index = {

        def users = User.filterUsers {
            and {
                like 'userName', 'Derek%'
            }
        }

        render users as JSON
    }
}

Also, you can find more about this here: Reference Documentation

Derek Slife
  • 20,750
  • 1
  • 18
  • 22