【问题标题】:(unsaved) data in groovy in many-many relationship(未保存)多对多关系中的groovy数据
【发布时间】:2014-02-03 02:01:41
【问题描述】:

我的数据域:

 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,但无法解决问题。

【问题讨论】:

  • 我认为teacherInst 是在teacherInst.addToTeacherCourse(teacherCourseA) 之后修改的,修改后您是否尝试再次保存teacherInst。
  • 我尝试保存teacherInst..仍然得到同样的错误..我也会更新代码..
  • 我不明白您为什么要创建 TeacherCourse 域。您可以直接将课程 c1 添加到教师实例。
  • 请将Teacher类的addToTeacherCourse方法添加到代码示例中。
  • @turbo 老师和课程之间存在多对多的关系...

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


【解决方案1】:

我认为一个问题出在 TeacherCourse 类的 id 上 - GORM (Hibernate) 需要它自己的单列 id 来处理持久上下文中的实例,在 ORM 中使用复合 id 绝不是个好主意。

让 GORM 有他的 id 并指定课程和老师一起是唯一的:

class TeacherCourse {
    Course course
    Teacher teacher

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

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

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

【讨论】:

【解决方案2】:
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));

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-11
    • 2012-01-03
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    相关资源
    最近更新 更多