Grails - adding custom fields (columns) to all domain objects - automatically

前端 未结 3 341
自闭症患者
自闭症患者 2021-01-22 04:50

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.

3条回答
  •  遥遥无期
    2021-01-22 05:48

    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

提交回复
热议问题