当使用hasMany和belongsTo时,我可以从源中导航,但不能从目标导航回到关系源。Grails hasMany反向?
例的Grails代码:
class School {
hasMany [students : Student]
}
class Student {
belongsTo [school : school]
}
// Following works
School scl = new School()
scl.addToStudents(new Student("firstStudent"))
scl.addToStudents(new Student("secondStudent"))
scl.save()
assertEquals(2, scl.students.size())
// Following does not work
School scl = new School()
scl.save() // so that it generated ID and persisted
Student std = new Student(school: scl)
std.save()
assertEquals(2, std.school.students) // This FAILS!
为什么,当我们从学生查找失败?我的理解是它应该起作用。
由于关于Hibernate的混淆,重读实例通常是空操作。如果你得到一个实例或者重新查询多个实例,并且它们已经与会话相关联,那么你只会返回相同的实例。您需要清除会话(并使用flush()来获得更好的效果),以使其有效。这很简单,例如'AnyDomainClass.withSession {it.flush(); it.clear()}' –
@Burt,很好用,当我清除会话! – 18bytes
如果您将您的评论移至回答,我会接受相同的答案。现在我无法接受它作为答案。尽管这是答案。 – 18bytes