How do I save GORM objects with multiple many-to-one relationships?

佐手、 提交于 2019-12-24 03:59:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!