I have a DomainClass with two variables and the user can only set one or the other. The one they don’t set is determined by some code in the setter of the one they set. So if they set A, B gets set what I want, and if they set B, A gets set what I want. The problem I’m having is that on .save() GORM or Hibernate or something is hitting the setters as well.
Here is my example domain added to a fresh grails 2.0 project called l2getset:
package l2getset
class ExampleDomain {
String thisIsA
String thisIsB
void setThisIsA(String thisIsA){
println "Hitting A Setter"
this.thisIsA = thisIsA
this.thisIsB = 'user set A'
}
void setThisIsB(String thisIsB){
println "Hitting B Setter"
this.thisIsB = thisIsB
this.thisIsA = 'user set B'
}
static constraints = {
}
}
And the bootstrap:
import l2getset.*
class BootStrap {
def init = { servletContext ->
def someExample = new ExampleDomain()
someExample.thisIsA = "Some String"
println "Some Example is: ${someExample.thisIsA} / ${someExample.thisIsB}"
someExample.save()
println "Some Example is: ${someExample.thisIsA} / ${someExample.thisIsB}"
}
def destroy = {
}
}
Prints:
| Running Grails application
Hitting A Setter
Some Example is: Some String / user set A
Hitting A Setter
Hitting B Setter
Some Example is: user set B / user set A
| Server running. Browse to http://localhost:8080/l2getset
How do I differentiate between when I “legitimately” set one of these and when GORM/Hibernate/PleaseExplain is just “playing around with my setters” before it persists my stuff?
This question: Why are setters in Grails called twice on save? appears to also touch on the issue, but I’m still left wondering what is going on and how to tackle my problem.
It’s happening because hibernate automatically uses setters when setting properties when you load. What you want is field-level access to these properties in hibernate.
See this for how to implement it.
Grails: field access with GORM