grailsgrails-ormnamed-querydomain-object

Grails domain Named query for a list


I have a simple Grails application. I have a couple of domains such as following. The scenario is Person has many Telephone (But person class does not have a list of telephone as a variable : Lazy Single-Ended Associations).

class Person implements Serializable {
    ....
}

class Telephone implements Serializable{
    String number
    static belongsTo = [person : Person]
    static mapping = {
        .....
        person lazy: false
    }
}

Now I have a requirement where I have to search the person by telephone numbers. I have a list of string telephone numbers. I need to get all the persons whom have at least one of that telephone number. I need to write namedQueries, but I'm quite new to this area. Is it possible to write named queries for this? Or do I need a mapping defined in Person class as

set telephone
static hasMany = [
        telephone: Telephone
]

And how would the namedQueries should be defined to suit my requirement

Thanks in advance


Solution

  • I believe for it to be able to see telephone from person you are correct that a

    set telephone
    static hasMany = [
            telephone: Telephone
    ]
    

    needs to be defined but once defined you can then just do:

     static namedQueries = {
           withSameTelephone {telephoneNumber -> 
                 telephone{ eq 'number' telephoneNumber }
           }
       }
    

    and use it like:

    Person.withSameTelephone('091511234512').list()
    

    I think you need to pass a list so

     static namedQueries = {
           withSameTelephoneInList {telephoneNumberList -> 
                 telephone{ 'in'( 'number' telephoneNumber) }
           }
       }
    

    so you could do:

    Person.withSameTelephoneInList(['091511234512','091511234513','091511234514']).list()