问题
Let's say I have the following hierarchy of domain classes.
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]
}
I tried two different ways to save a school, teacher, and student.
Attempt 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)
It appears to save properly but when I run:
println(school.students*.name)
It prints null.
So I decided to try a different approach.
Attempt 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)
Here I tried several combinations of saves and I always got an error about a required field being null. In this case the error was
JdbcSQLException: NULL not allowed for column "TEACHER_ID"
I would greatly appreciate if someone could explain why my attempts failed and what the proper way to go about creating the data is.
回答1:
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)
来源:https://stackoverflow.com/questions/12223066/how-do-i-save-gorm-objects-with-multiple-many-to-one-relationships