Grails单向多对多

时间:2013-04-25 08:16:00

标签: grails gorm

我有Java / JavaEE背景,最近开始了Grails项目。

当我编写域模型时,有一个要求:单向多对多。我知道它应该在Jpa / Hibernate中。我在grails中快速搜索了一下,似乎在Grails中不支持它,有些人建议使用映射类(没有示例应该怎么做)。

任何人都可以给我一个例子,或者我应该如何做这个要求?

例如:

class Teacher {
static hasMany: [students: Student]
}

class Student {
    static belongsTo: Teacher
    static hasMany: [teachers: Teacher]
}

上面的代码是使用Grails文档中的双向多对多来完成的。什么是单向多对多的代码?

此外,只有学生才能有教师参考,在教师课堂上,它无法获得学生名单。

感谢。

2 个答案:

答案 0 :(得分:1)

我使用了三个班级,如老师,学生和中级课程。从学生我们可以访问教师参考。在教师方面,我们无法访问学生。

class Teacher {
String name

}

class Student {
    String name
    static hasMany      = [teachers:StuTeach]

}

class StuTeach {

    static constraints = {
    }
    static belongsTo    = [teacher:Teacher,student:Student]
}

在bootstrap中,

        def t1=new Teacher(name:"t1")
        t1.save(flush:true)
        def t2=new Teacher(name:"t2")
        t2.save(flush:true)

        def stu=new Student(name:"s1")
        stu.save(flush:true)

        def stuteach1=new StuTeach()
        stuteach1.student=stu
        stuteach1.teacher=t1
        stuteach1.save(flush:true)

        def stuteach2=new StuTeach()
        stuteach2.student=stu
        stuteach2.teacher=t2
        stuteach2.save(flush:true)

        stu.addToTeachers(stuteach1)
        stu.addToTeachers(stuteach2)

        stu.save(flush:true)
        println stu.teachers.teacher

答案 1 :(得分:0)

hibernate支持单向多对多关系,Grails可以支持这种关系:

http://blog.exensio.de/2013/12/unidirectional-many-to-many.html

相关问题