10

Hello I have the follwing domain classes.

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

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

I want to find the Students taking Course (with id 1), with age 7.

Could I do that with dynamic finder or criteria builder or HQL?

I do not want to do following as it load all students so inefficient:

def course = Course.get(1);
course.students.findAll{ it.age == 7 }
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
enesness
  • 3,123
  • 5
  • 31
  • 33

2 Answers2

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

It's in GORM doc, section "Criteria/Querying Associations".

Victor Sergienko
  • 13,115
  • 3
  • 57
  • 91
-2

You can use a dynamic finder:

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

By using load() instead of get() you avoid retrieving the whole Course instance and just reference its id.

Another option is HQL:

def students = Student.executeQuery(
   'from Student s where s.course.id = :courseId and s.age = :age',
   [courseId: 1, age: 7])
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • 3
    Hello Burt. Student does not have "course" field, it has "courses". I can not do findByCourse, I can do findByCourses but it may I compare collections. – enesness Jun 12 '11 at 14:08