How can I automatically populate a custom column in my domain class to equal the ID? For example:
//Domain class
class myData {
Integer columnToEqualID
static mapping = {
columnToEqualID = id //how to I get something similar to this to work?
}
}
One approach that isn't foolproof but should work if you're careful is to override the setter for id
.
This relies on the fact that when you declare a persistent like columnToEqualID
, Groovy converts that to a private field and adds in a getter and setter method (but only if you don't use any scope modifier, so if you including private
, public
, etc. then it will stay as you declared it). So Integer columnToEqualID
basically becomes
private Integer columnToEqualID
public void setColumnToEqualID(Integer value) {
columnToEqualID = value
}
public Integer getColumnToEqualID() {
return columnToEqualID
}
This isn't Groovy runtime metaprogramming magic - it's actually in the bytecode, so you can see all of this if you decompile the .class file.
This is cool because at any time you can add your own getter and/or setter and Groovy won't add the default version(s), so you can add logic for what to set and/or what to get.
Grails adds a Long id
property for you, so there's a getId
and setId
method in every domain class, and you can add your own that does the same as the default, plus the custom behavior.
So this should do what you want:
void setId(Long id) {
this.id = id
columnToEqualID = id
}
This won't keep you from changing the value of columnToEqualID
independently though, so that's the "if you're careful" bit - you and the other developers need to be sure to be aware of this nonstandard behavior.
You could probably address that issue by overriding the setter for columnToEqualID
too, e.g.
void setColumnToEqualID(Integer value) {
if (value != id) {
// handle the problem
}
this.columnToEqualID = value
}