假设我有两个域类:
class User {
String name
Role role
}
class Role {
String name
static belongsTo = [user: User]
}
我创建了一些记录:
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()
我现在如何按角色选择用户?我希望能够执行以下操作之一:
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
域类是否可以使用动态 find* 方法查找其他关联的域类?我可以使用namedQueries来做到这一点,但id而不是因为我不想为域类之间的每个关系写出它们
最佳答案
如果您事先检索需要查找的对象,则 findBy* 和 findAllBy* 方法似乎确实有效。看来它必须是对数据库中对象的精确(非陈旧?)引用,因此您不能创建一个“看起来”像您要查找的对象的新对象,它实际上必须是那个对象。
因此,为了找到所有角色为“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
关于hibernate - Grails 域类查询 - 如何通过链接到另一个域类的字段进行查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3723607/