如何解决Grails:如何在多对多映射中查询对象?
| 您好,我有以下域类。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])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。