2012-08-31 77 views
2

比方说,我有以下层次结构的域类。如何保存具有多个多对一关系的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) 

它打印

所以我决定尝试一种不同的方法。

尝试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:NULL不允许列“TEACHER_ID”

我将不胜感激,如果有人可以解释为什么我的尝试失败,什么正确的方式去创造数据是。

回答

4
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) 
+0

这给了我以下异常:JDBCExceptionReporter - NULL不允许列 “TEACHER_ID”; SQL语句: 插入学生(id,版本,名称,school_id,teacher_id)值(空,?,?,?,?) –

+0

保存在'school.addToStudents'之前的教师我编辑的代码 –

+0

工作正常。非常感谢! –