我有两个Domain类
class Reputation {
int value
static hasMany = [events: Event]
static mapping = {
value defaultValue: 0
}
}
和
class Event {
int point
static belongsTo = [reputation: reputation]
}
在ReputationService中,我做了类似的事情
reputation.addToEvents(new Event())
reputation.save() //which gonna make event and reputation save at once
但我希望将声誉值更新为:value是所有事件的总和'点。所以我补充说:
Class Event {
//....
def afterInsert() {
reputation.value += point
reputation.save()
}
}
但它不起作用:我总是有一个Reputation.value = 0.
有什么问题?我该怎么做呢?
答案 0 :(得分:1)
如果仔细查看有关事件和GORM的Grails documentation,您会注意到:
因为在Hibernate使用刷新时会触发事件 像save()和delete()这样的持久化方法不会产生对象 除非您使用新会话运行操作,否则将被保存。
所以,在你的情况下,它可能是这样的:
Class Event {
//....
def afterInsert() {
Event.withNewSession {
reputation.value += point
reputation.save()
}
}
}