如何保存具有多个多对一关系的GORM对象? [英] How do I save GORM objects with multiple many-to-one relationships?
问题描述
class School {
字符串名称
static hasMany = [老师:老师,学生:学生]
}
班级老师{
字符串名称
static belongsTo = [school:School]
static hasMany = [students:Student]
}
class学生{
字符串名称
static belongsTo = [学校:学校,教师:教师]
}
我尝试了两种不同的方式来保存学校,老师和学生。
尝试1:
def school = new School (名称:学校)。save()
def teacher = new教师(名称:教师,学校:学校).save()
def student = new Student(name:Student ,学校:学校,老师:老师).save(flush:true)
但是当我运行时:
println(school.students * .name)
它打印 null 。
所以我决定尝试一种不同的方法。 尝试2:
def学校=新学校(名称:学校)
def老师=新老师(姓名:老师)
def学生=新学生(名称:学生)
teacher.addToStudents (学生)
school.addToStudents(学生)
school.addTo教师(教师)
school.save(failOnError:true,flush:true)
在这里,我尝试了几种保存组合,并且我总是收到有关必填字段为空的错误。在这种情况下,错误是:
JdbcSQLException:NULL不允许列TEACHER_ID
如果有人能解释为什么我的尝试失败以及创建数据的正确方式是什么,我将不胜感激。
>解决方案
def school = new School(name:School)。save(flush:true)
def teacher = new Teacher(name :老师)
学生(名称:学生,老师:老师)$ b $ school.addTo教师(老师)
teacher.save(刷新:true)
def学生= b school.addToStudents(学生)
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)
这篇关于如何保存具有多个多对一关系的GORM对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!