Reputation: 1192
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
Upvotes: 0
Views: 840
Reputation: 897
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()
Upvotes: 2
Reputation: 20699
I'd stick with single-ended o2m, and put a named query like:
class Telephone {
...
static namedQueries = {
byPerson{ Person p ->
eq 'person', p
}
}
}
and call it like:
Person p = Person.get 1111
def telephones = Telephone.byPerson p
On the other hand you can use a simple findAllBy*
query:
Person p = Person.get 1111
def telephones = Telephone.findAllByPerson p
Upvotes: 0