许多关系中的(未保存的)数据在groovy中

时间:2014-02-03 02:01:42

标签: grails gorm grails-domain-class grails-controller

我的数据域:

 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']
}

}

在我的控制器中:

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));

}

输出 net.school.teacher.TeacherCourse :(未保存)

教师和教师课程保存在数据库中(PostgreSQL)。当我尝试从列表中检索值时,我收到(未保存的)消息。我不知道为什么会这样。任何帮助,将不胜感激。我查了link,但无法解决问题。

2 个答案:

答案 0 :(得分:1)

我认为问题在于TeacherCourse类的ID - GORM(Hibernate)需要它自己的单列id来处理持久化上下文中的实例,这使得复合id在ORM中永远不是好主意。

让GORM拥有自己的身份,并指明课程和老师是唯一的:

class TeacherCourse {
    Course course
    Teacher teacher

    static mapping = {
        course unique: 'teacher'
    }
}

在这里,当域实例的id为null时,您可以检查是否从toString()返回net.school.teacher.TeacherCourse : (unsaved)

http://jira.grails.org/browse/GRAILS-8072

答案 1 :(得分:0)

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).save(true)
 def teacherCourseB = new TeacherCourse(teacher:teacherInst, course:c2).save(true)

 //TRY!
 println(Teacher.findById(teacherInst.id).teacherForCourses.get(0));

}