문제

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.

도움이 되었습니까?

해결책

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top