Amio.io
Amio.io

Reputation: 21575

Grails Domain Constructor is not Groovy Constructor

Executing this peace of code

class DefObject{
  String a
  def b
}

def c = new DefObject(a:1, b:2);

yields different results in Grails and in Groovy.

Groovy

assert c.a == 1
assert c.b == 2 

Grails Domain Class

assert c.a == 1 
assert c.b == null

How can I make Grails Domain to accept a value for b?

Upvotes: 1

Views: 423

Answers (1)

Burt Beckwith
Burt Beckwith

Reputation: 75671

This is because in domain classes, only "bindable" properties can be set via the map constructor. You can override whether a property is bindable or not (e.g. the id property isn't for security reasons, but if you know what you're doing you can configure it to be).

Untyped properties like b are not persistent since GORM/Hibernate has no way of knowing how to store the data if it's just specified with def or Object. So they're not bindable since they're not persistent, and they're ignored by the customized map constructor.

This is a convenient feature for other reasons, e.g. it allows new DefObject(params) to work without complaining about query parameters in the params map that don't correspond to properties in the domain class, e.g. controller and action. Using the Groovy constructor, if you have a value to the map where the key doesn't correspond to a class property, a groovy.lang.MissingPropertyException is thrown but these are ignored in domain classes.

Upvotes: 5

Related Questions