views:

95

answers:

1

Hello,

Lets say I have two domain classes:

class User {
  String name
  Role role
}

class Role {
  String name
  static belongsTo = [user: User]
}

and I create some records:

def r1 = new Role(name: "role1").save()
def r2 = new Role(name: "role2").save()
new User(name: "user1", role: r1).save()
new User(name: "user2", role: r2).save()
new User(name: "user3", role: r1).save()

How can I now select my users by role? I would expect to be able to do one of the following:

def role = Role.findByName("role1"); //returns a Role with [ id:1 name:"role1" ]
User.findAllByRole(role) //returns null
User.findAllByRole(new Role(name: "role1")) //returns null
User.findAllByRole(role.id) //returns null
User.findAllByRole(id: role.id) //returns null

Is it possible for a domain class to find other associated domain classes using the dynamic find* methods? I can do it using namedQueries, but id rather not because I dont want to have to write them out for every relationship I have between domain classes

A: 

It appears that the findBy* and findAllBy* methods DO work, if you retrieve the object you need to find beforehand. It appears that it must be an exact (non-stale?) reference to an object in the database, so you cannot create a new object that "looks" like the object you want to find by, it actually has to be that object.

So, in order to find all the Users with the role of "role1":

def role = Role.findByName("role1")
def users = User.findAllByRole(role)
for (def user in users) {
 println("User ${user.name} matched the query, with role: ${user.role.name}")
}
//prints:
//User user1 matched the query, with role role1
//User user3 matched the query, with role role1
Erin Drummond
FYI: The code in your question *was* retrieving the role using a find. It wasn't just creating one with the same data.
Javid Jamae