Grails:如何在多对多映射中查询对象?

时间:2011-06-11 15:29:10

标签: grails gorm grails-domain-class

您好我有以下域类。

class Student {
   int age
   static hasMany = [courses:Course]
}

class Course {
   String name
   static hasMany = [students:Student]
}

我想找到7岁的学生参加课程(身份1)。

我可以使用动态查找器或条件构建器或HQL吗?

我不想这样做,因为它加载所有学生效率低下:

def course = Course.get(1);
course.students.findAll{ it.age == 7 }

2 个答案:

答案 0 :(得分:22)

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

位于GORM doc,“查询关联”部分。

答案 1 :(得分:-2)

您可以使用动态查找器:

def students = Student.findByCourseAndAge(Course.load(1), 7)

使用load()代替get(),您可以避免检索整个课程实例,只需引用其ID。

另一个选择是HQL:

def students = Student.executeQuery(
   'from Student s where s.course.id = :courseId and s.age = :age',
   [courseId: 1, age: 7])
相关问题