如何使用多个多对一关系保存GORM对象?

Eri*_*las 2 grails groovy grails-orm

假设我有以下层次的域类.

class School {
   String name
   static hasMany = [teachers: Teacher, students: Student]
}

class Teacher {
   String name
   static belongsTo = [school: School]
   static hasMany = [students: Student]
}

class Student {
   String name
   static belongsTo = [school: School, teacher: Teacher]
}
Run Code Online (Sandbox Code Playgroud)

我尝试了两种不同的方法来拯救学校,老师和学生.

尝试1:

def school = new School(name: "School").save()
def teacher = new Teacher(name: "Teacher", school: school).save()
def student = new Student(name: "Student", school: school, teacher: teacher).save(flush: true)
Run Code Online (Sandbox Code Playgroud)

它看起来保存得当但是我跑的时候:

println(school.students*.name)
Run Code Online (Sandbox Code Playgroud)

它打印null.

所以我决定尝试不同的方法.

尝试2:

def school = new School(name: "School")
def teacher = new Teacher(name: "Teacher")
def student = new Student(name: "Student")
teacher.addToStudents(student)
school.addToStudents(student)
school.addToTeachers(teacher)
school.save(failOnError: true, flush: true)
Run Code Online (Sandbox Code Playgroud)

在这里,我尝试了几种保存组合,我总是得到一个关于必填字段为空的错误.在这种情况下,错误是

JdbcSQLException:列"TEACHER_ID"不允许NULL

如果有人能够解释我的尝试失败的原因以及创建数据的正确方法,我将不胜感激.

AA.*_*AA. 5

def school = new School(name: "School").save(flush: true)
def teacher = new Teacher(name: "Teacher")
school.addToTeachers(teacher)
teacher.save(flush: true)
def student = new Student(name: "Student", teacher: teacher)
school.addToStudents(student)
Run Code Online (Sandbox Code Playgroud)