Eric Milas
Eric Milas

Reputation: 1847

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

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.

Upvotes: 3

Views: 3568

Answers (1)

AA.
AA.

Reputation: 4606

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)

Upvotes: 5

Related Questions