Grails - adding custom fields (columns) to all dom

2019-02-27 08:56发布

问题:

By default when you create a domain class, it will automatically add "id" and "version" column for all the domain classes (tables). What if I want to add a column say for e.g. "isChecked" and this should be added automatically to all the domain classes (i.e tables) similar way "id" and "version" columns are added. How can I achieve this and also if I don't want to have "isChecked" for a specific domain class, I should also be able to do that.

How can I do this in Grail 1.3.7?

Thank You. Jay Chandran

Edit: Can I get more inputs? Suggested answers did not work!

回答1:

You could use the meta programming magic that Groovy provides for this sort of thing, however, I would probably just go a more typical route and use inheritance. Create a parent domain that contains isChecked (and anything else you need) and have your domains that require them extend that class.



回答2:

I would recommend creating a plugin that modifies (adds the property) your domain artifacts. You can read more about plugins and artifacts. You could then easily add a static property (e.g. static nochecked = true) to filter out domain artifacts you don't want to add the new property to as you see fit.



回答3:

You can do this using metaprogramming. The code that adds the property should be run either in the doWithDynamicMethods closure of a plugin or from Bootstrap.groovy. If using the plugin approach, something like this should work:

def doWithDynamicMethods = {ctx ->
  application.domainClasses
        .findAll {it.simpleName.startsWith('S')}.metaClass.each {domainMetaClass ->

    Integer fooVal = 0

    domainMetaClass.getFoo = {-> fooVal}
    domainMetaClass.setFoo = {Integer newFooVal -> fooVal = newFooVal}
  }
}

The code above should add a Integer foo property to every domain class whose name starts with 'S'. I haven't tested this code, so it probably doesn't work. To see an example that you can be more confident about:

  1. Find a plugin that adds that modifies domain classes (e.g. adds a field or method)
  2. Download it
  3. Look at the code in the plugin descriptor's doWithDynamicMethods closure
  4. Copy, paste and adapt to your needs