Frage

When using hasMany and belongsTo, i can navigate from the source but not from target backwards to source of relationship.

Example Grails code:

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!

Why is that when we lookup from Student it fails? My understanding is that it should work.

War es hilfreich?

Lösung 2

By Burt Beckwith

Re-reading instances is typically a no-op due to confusion about Hibernate. If you get() an instance or re-query for multiple and they're already associated with the session you'll just get the same instances back. You need to clear the session (and flush() for good measure) for this to be valid. This is pretty simple to do, e.g. AnyDomainClass.withSession { it.flush(); it.clear() } – Burt Beckwith 6 hours ago

This solution works!

Andere Tipps

The last line should be:

assertEquals(1, std.school.students.size())

instead of

assertEquals(2, std.school.students)

Try also to re-read objects state before assertion.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top