如何使用多个多对一关系保存GORM对象?

时间:2012-08-31 22:11:00

标签: grails groovy gorm

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

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

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

1 个答案:

答案 0 :(得分: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)