當使用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