Search code examples
hibernategrailsgrails-orm

GRAILS GORM how to update a parent property automatically when saving a child


I have two objects.

TimeFrame{

  hasMany=[activity:Activity]

   Date startTime
   Date endTime
   Integer activeActivities

}

Activity{
   belongsTo=[timeFrame:TimeFrame]

  String name
  String description
  Date start
  Date end

}

Anytime I insert,update, or delete an Activity I want to automatically update the number of activeActivities a timeframe has. But when I add GROM event methods like...

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)
    }
}

I get the error

  null id in com.application.tracker.Activity entry (don't flush the Session after an exception occurs).

What's a way around this?


Solution

  • The reason why your save is failing inside your afterUpdate is because you aren't using withNewSession. The documentation points out this detail.

    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.