1

I have the following domain class:

class Car{

 int hp
 Date registrationDate

}

Now what I'm trying to do is create a named query that enables me to do something like this:

Car.getCarsByYear(2011)

and

Car.getCarsByYearMonth(2011,11)

I'n not sure the second one is possible or if the only way to do it is by having 2 named queries, one for year and one for month.

How do you specify the month/year for a date in a named query? I took some wild shots and tried googling it but I came up with nothing.

marko
  • 3,736
  • 6
  • 29
  • 46

1 Answers1

2

You can pass parameters to your namedquery :

    static namedQueries = {
    getCarsByYearMonth { int year, int month ->
        println "year:"+year
        println  "month:"+month
        def now = Date.parse("yyyy-MM", "${year}-${month}")
        eq 'registrationDate', now
    }
}

and call it like this :

 def search() {
    render Car.getCarsByYearMonth(2012,2).list()
}
Alidad
  • 5,463
  • 1
  • 24
  • 47
  • 1
    One note: you may want to use the field from marko's question, `registrationDate`, instead of the generic `date`, because it's a little confusing to read. – OverZealous Mar 06 '12 at 06:02
  • 1
    I assume he wants the cars whose month/year is equal to the params, not greater than – Dónal Mar 06 '12 at 10:14