Grails Composition: addTo * in Constructors

I have the following simplified model in Grails:

  • A DataBlock

    consists of multiple sorted objects ConfigPreset

    .

In ConfigPreset I have

static belongsTo = [dataBlock: DataBlock]

      

and the DataBlock class contains:

List presets
static hasMany = [presets: ConfigPreset]

DataBlock() {
    addToPresets(new ConfigPreset())
}

      

The overloaded constructor returns: No method signature: [...]. addToPresets () is applicable for argument types: (ConfigPreset) values: [ConfigPreset: null].

But why is my ConfigPreset instance null? If I try to create a DataBlock object eg. BootStrap.groovy with unmodified ctor and addToPresets (...) call on it, it works.

+2


a source to share


2 answers


Your example may not work.

The assignment static belongsTo = [dataBlock: DataBlock]

inside ConfigPreset

means that you cannot create an instance ConfigPreset

without specifying the owner DataBlock

.

So basically the following statement

new ConfigPreset()

will always return null

unlike

new ConfigPreset(dataBlock: aDataBlock)

which will return a valid instance ConfigPreset

.



The method addToXXX

basically does the following:

  • Instantiate XXX (as described below)
  • Add the newly created instance XXX to the instance this

In your case, it cannot create ConfigPreset

(step 1), since the instance DataBlock

has not been created yet (yours are in the constructor)

If you want to bind the ConfigPreset automatically whenever you create a DataBlock, you can do so using Gorm Events by adding a callbalck to the beforeInsert event.

Or you can uninstall belongsTo

and it new ConfigPreset()

will work.

0


a source


Grails runs your domain classes (and other artifacts) at least once during startup for its init code. This happens before dynamic methods are added, hence the exception. It works in BootStrap since everything is set up in this step. Note that nothing is empty - you just see the toString () of the domain class, which prints the name and ID, and since this is a new instance, the ID is null.



You can use the beforeInsert callback for this, see http://grails.org/doc/latest/guide/5.%20Object%20Relational%20Mapping%20%28GORM%29.html#5.5.1%20Events%20and% 20Auto% 20Timestamping

+1


a source







All Articles