【问题标题】:How do I save GORM objects with multiple many-to-one relationships?如何保存具有多个多对一关系的 GORM 对象?
【发布时间】:2012-08-31 22:10:59
【问题描述】:

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

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

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

【问题讨论】:

    标签: grails groovy grails-orm


    【解决方案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)
    

    【讨论】:

    • 这给了我以下异常:JDBCExceptionReporter - NULL 不允许用于列“TEACHER_ID”; SQL语句:插入学生(id,版本,名称,school_id,teacher_id)值(null,?,?,?,?)
    • 但是这些指令会将数据保存在连接表中吗?数据库中的“链接数据”将保存在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多