Reputation: 155
I have two Domain class
class Reputation {
int value
static hasMany = [events: Event]
static mapping = {
value defaultValue: 0
}
}
and
class Event {
int point
static belongsTo = [reputation: reputation]
}
In ReputationService, I do something like this
reputation.addToEvents(new Event())
reputation.save() //which gonna make event and reputation save at once
But I want value in Reputation to be updated to : value is the sum of all events' point. So I add :
Class Event {
//....
def afterInsert() {
reputation.value += point
reputation.save()
}
}
But it doesn't work: I always have a Reputation.value = 0.
What is wrong ? And how can I do this properly ?
Upvotes: 0
Views: 157
Reputation: 24776
If you look closely at the Grails documentation regarding Events and GORM you will notice it says:
Since events are triggered whilst Hibernate is flushing using persistence methods like save() and delete() won't result in objects being saved unless you run your operations with a new Session.
So, in your case it may be something like this:
Class Event {
//....
def afterInsert() {
Event.withNewSession {
reputation.value += point
reputation.save()
}
}
}
Upvotes: 1