问题描述
|
您好,我有以下域类。
class Student {
int age
static hasMany = [courses:Course]
}
class Course {
String name
static hasMany = [students:Student]
}
我想找到年龄7岁的参加课程的学生(ID为1)。
我可以使用动态查找器或条件构建器或HQL来做到这一点吗?
我不想做以下事情,因为它使所有学生效率低下:
def course = Course.get(1);
course.students.findAll{ it.age == 7 }
解决方法
def studs = Student.withCriteria {
eq(\'age\',7)
courses {
eq(\'id\',1)
}
}
它位于GORM文档的“查询关联”部分中。
, 您可以使用动态查找器:
def students = Student.findByCourseAndAge(Course.load(1),7)
通过使用load()
而不是get()
,您可以避免检索整个Course实例,而只需引用其ID。
另一个选择是HQL:
def students = Student.executeQuery(
\'from Student s where s.course.id = :courseId and s.age = :age\',[courseId: 1,age: 7])