I’m trying to load a list of Evaluations in a class named Contributor but I’m missing something as I cannot get my test passing.
My test is creating and saving objects as expected because when I do Evaluations.list() and Contributor.list() and print the values I see the data I saved.
Furthermore, when I select an Evaluation and print the value of its ‘contributor’ property it appears to be correct.
However, when I select a Contributor and print the values of its ‘evaluations’ property it is null.
I assume my mapping is the problem?
class Contributor {
String name
static hasMany = [evals:Evaluation]
static mapping = {
id column: 'user_id'
evals joinTable:[name:'evaluation', column:'eval_id', key:'eval_user_id']
version false
}
}
class Evaluation {
Contributor contributor
String comment
static mapping = {
id column:'eval_id'
contributor column:'eval_user_id'
version false
}
}
Thanks.
You shouldn’t assign
evalslikecontributor.evals = [eval]. Rather invoke a dynamic methodaddTo*():contributor.addToEvals(eval). This will create a Hibernate collection forevalswhich will be persisted later.The first one didn’t work because Grails doesn’t assign other end of association when you assign
eval.contributor, i.e. it doesn’t callcontributor.addToEvals(eval). I have no idea why – there must be some implementation reason.So
contributorremains with the same emptyevalsin Hibernate cache. If it falls out of cache and you re-read it, it will haveevalsfilled, because the association is mapped only onEvaltable’s foreign key.Empty
evalsare null – it’s another Hibernate feature: when a collection is empty, it can be null. Just know it.Here’s an good short post explaining some Hibernate internals: http://blog.xebia.com/2008/03/advanced-hibernate-proxy-pitfalls/