Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to dynamically add a property / field to a domain class in Grails?
    primarykey
    data
    text
    <p>For a project I'm currently working on I need to dynamically add properties to a domain class and persist them later in the database. In general, I need a key/value store attached to a "normal" domain class. Sadly I cannot use a NoSQL database (e.g. Redis). </p> <p>My approach would be to handle the additional properties on a <code>save()</code> by identifying them within <code>afterInsert</code> or <code>afterUpdate</code> and writing them to another table - I would prefer not to use a map property within the domain class but an additional "Field" table (to better support searches).</p> <p>I tried to add properties using the <strong>metaClass approach</strong>:</p> <pre><code>person.metaClass.middlename = "Biterius" assert person.middlename == "Biterius" // OK </code></pre> <p>This works and I can identify the additional properties in the afterInsert/afterUpdate methods but it seems that I cannot change the value thereafter - i.e., the following does not work:</p> <pre><code>person.middlename = "Tiberius" assert person.middlename == "Tiberius" // FAIL </code></pre> <p>Then I tried an <strong>Expando approach</strong> by extending the Person class by the Expando class (directly ("Person extends Expando") and via an abstract intermediate class ("Person extends AbstractPerson" and "AbstractPerson extends Expando")). </p> <pre><code>def person = new Person() assert person in Person // OK assert person in AbstractPerson // OK assert person in Expando // OK </code></pre> <p>Both variants did not work - I could assign values to arbitrary "properties" but the values were not stored!</p> <pre><code>person.mynewproperty = "Tiberius" // no MissingPropertyException is thrown println person.mynewproperty // returns null </code></pre> <p>So how can I add properties to a domain class programmatically during runtime, change them and retrieve them during afterInsert or afterUpdate in order to "manually" store them in a "Fields" table? </p> <p>Or am I doing something completely wrong? Are there other / simpler ways to do this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload