My Data Domain:
class Course{
List teacherCourse
static hasMany = [courseByMultipleTeacher:TeacherCourse]
}
class Teacher{
String name
List teacherForCourses
static hasMany = [teacherForCourses:TeacherCourse]
}
class TeacherCourse{
Course course
Teacher teacher
static mapping={
id composite: ['teacher','course']
}
}
And in my controller:
save(){
Teacher teacherInst = new Teacher()
teacherInst.name = "T1"
teacherInst.save(flush:true)
Course c1 = Course.findById(3)
Course c2 = Course.findById(4)
def teacherCourseA = new TeacherCourse(teacher:teacherInst, course:c1)
def teacherCourseB = new TeacherCourse(teacher:teacherInst, course:c2)
teacherInst.addToTeacherCourse(teacherCourseA)
teacherInst.addToTeacherCourse(teacherCourseB)
teacherInst.save(flush:true)
//Output is: (unsaved) . Why?
println(Teacher.findById(teacherInst.id).teacherForCourses.get(0));
}
Output net.school.teacher.TeacherCourse : (unsaved)
The Teacher and TeacherCourse gets saved in database (PostgreSQL). I get the (unsaved) message when ever I try to retrieve the value from the list. I am not sure why is that. Any help would be appreciated. I looked up this link, but could not solve the problem.
I think a problem is with the id of TeacherCourse class - GORM (Hibernate) needs it's own single column id to handle instances in persistent context, making composite id is never good idea in ORM.
Let GORM have his id and just specify that course and teacher together are unique:
class TeacherCourse {
Course course
Teacher teacher
static mapping = {
course unique: 'teacher'
}
}
Here you can check that net.school.teacher.TeacherCourse : (unsaved) is returned from toString() when id of the domain instance is null:
http://jira.grails.org/browse/GRAILS-8072
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With