3

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

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)

它似乎可以正确保存,但是当我运行时:

println(school.students*.name)

它打印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)

在这里,我尝试了几种保存组合,但总是收到有关必填字段为空的错误。在这种情况下,错误是

JdbcSQLException:列“TEACHER_ID”不允许为 NULL

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

4

1 回答 1

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)
于 2012-08-31T22:30:29.163 回答