10

您好,我有以下域类。

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 }
4

2 回答 2

24
def studs = Student.withCriteria {
  eq('age', 7)
  courses {
    eq('id', 1)
  }
}

它在GORM doc的“Criteria/Querying Associations”部分。

于 2011-06-11T15:45:33.170 回答
-2

您可以使用动态查找器:

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])
于 2011-06-11T16:09:29.697 回答