GRAILS GORM 如何在保存子项时自动更新父项 属性
GRAILS GORM how to update a parent property automatically when saving a child
我有两个对象。
TimeFrame{
hasMany=[activity:Activity]
Date startTime
Date endTime
Integer activeActivities
}
Activity{
belongsTo=[timeFrame:TimeFrame]
String name
String description
Date start
Date end
}
每当我插入、更新或删除一个 Activity 我想自动更新一个时间范围内的 activeActivities 的数量。但是当我添加 GROM 事件方法时...
def afterUpdate(){
try{
def num=0;
def now=new Date();
timeFrame.activities.each{i->
if(!i.end || i.end < now){
num+=1;
}
}
timeFrame.activeActivities=num;
timeFrame.save();
}
catch(e){
log.debug('Unable to update active tally on Activity update:'+e)
}
}
我收到错误
null id in com.application.tracker.Activity entry (don't flush the Session after an exception occurs).
有什么解决办法?
你的 save
在你的 afterUpdate
中失败的原因是你没有使用 withNewSession
。 documentation 指出了这个细节。
Notice the usage of withNewSession method above. 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.
Fortunately the withNewSession method lets you share the same
transactional JDBC connection even though you're using a different
underlying Session.
我有两个对象。
TimeFrame{
hasMany=[activity:Activity]
Date startTime
Date endTime
Integer activeActivities
}
Activity{
belongsTo=[timeFrame:TimeFrame]
String name
String description
Date start
Date end
}
每当我插入、更新或删除一个 Activity 我想自动更新一个时间范围内的 activeActivities 的数量。但是当我添加 GROM 事件方法时...
def afterUpdate(){
try{
def num=0;
def now=new Date();
timeFrame.activities.each{i->
if(!i.end || i.end < now){
num+=1;
}
}
timeFrame.activeActivities=num;
timeFrame.save();
}
catch(e){
log.debug('Unable to update active tally on Activity update:'+e)
}
}
我收到错误
null id in com.application.tracker.Activity entry (don't flush the Session after an exception occurs).
有什么解决办法?
你的 save
在你的 afterUpdate
中失败的原因是你没有使用 withNewSession
。 documentation 指出了这个细节。
Notice the usage of withNewSession method above. Since events are triggered whilst Hibernate is flushing using persistence methods like
save()
anddelete()
won't result in objects being saved unless you run your operations with a new Session.Fortunately the withNewSession method lets you share the same transactional JDBC connection even though you're using a different underlying Session.