Search code examples
grailsdatenamed-query

Named query for dates (month and year)


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.


Solution

  • 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()
    }