比方说,我有域类的层次结构如下。
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)
它打印空 。
所以我决定尝试一种不同的方法。
尝试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”
我将不胜感激,如果有人可以解释为什么我的尝试失败,什么正确的方式去创造的数据。