Grails 如何保存具有多个多对一关系的GORM对象?

Grails 如何保存具有多个多对一关系的GORM对象?,grails,groovy,gorm,Grails,Groovy,Gorm,假设我有以下域类的层次结构 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

假设我有以下域类的层次结构

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]
}
我尝试了两种不同的方法来拯救学校,老师和学生

尝试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)
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)
它似乎保存正确,但当我运行时:

println(school.students*.name)
它打印空

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

尝试2:

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)
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)
在这里,我尝试了几种保存组合,但我总是得到一个关于必填字段为空的错误。在这种情况下,错误是

JdbcSQLException:列“教师ID”不允许为NULL


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

这给了我以下例外情况:JDBCExceptionReporter-NULL不允许用于列“教师ID”;SQL语句:在学生(id、版本、名称、学校id、教师id)中插入值(null、、、、、、?),但这些指令是否将数据保存在联接表中?数据库中“链接数据”将保存在何处?
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)