Search code examples
grailsgrails-ormgrails-2.0

Grails getter writing to database?


I am running into some behavior that I did not expect. I have an object that has a status. This object has two states, in progress and closed out. While the object is in-progress I want the status to be calculated and not saved in the database... However, once I close it out/finalize it the status needs to be saved.

The following is the way I tried to set things up:

class Assessment{
  AssessmentStatus status
  List<Score> scores
  static hasMany = [scores: Score]


  AssessmentStatus getStatus() {

    if(status){
      return status
    }

    if (!scores || event.eventDateTime.after(new Date())) {
      return AssessmentStatus.PRE_EVENT
    }

    scores.each{ 
      if (it.incompleteReason){
        return AssessmentStatus.INCOMPLETE
      }
    }

    if (!getPassing()) {
      return AssessmentStatus.FAIL
    }

    return AssessmentStatus.PASS
  }

  Boolean getPassing() {
    def passing = Boolean.TRUE
    this.scores.each {score ->
      if (!score.passingScore){
        passing = Boolean.FALSE
      }
    }
    return passing
  }
}

As you can see with the code I was expecting to check to see I was expecting to check if status was null. If status is not null then return it. If it is null then do some other calculation. But... For some reason or another the calculated status is getting persisted to the database. Now I know I could always go in and add:

if(finalized){
  return status
}

VS the if(status) and I would get the proper return. BUT... I don't want junk data in the database. Another way to do it would be to not override the getter...

My question basically boils down to. Why is overriding the getter writing to the database and is there a way around it.


Solution

  • All fields are persisted to the database unless you explicitly define otherwise. The fact you are overriding a getter doesn't automatically tell Grails that you do not want to persist that property to the database. To do that you must define the property as transient:

      static transients = ['status']