Grails: How to query objects in many to many mapping?

北慕城南 提交于 2019-12-22 04:06:14

问题


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 }

回答1:


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

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




回答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])


来源:https://stackoverflow.com/questions/6316761/grails-how-to-query-objects-in-many-to-many-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!