Common beforeInsert and beforeUpdate methods from Mixin for common domain columns

▼魔方 西西 提交于 2019-12-02 03:02:48

FYI, use of groovy.lang.Mixin is strongly discouraged (by the Groovy project leader, for one). If you have to use mixins you should use grails.util.Mixin instead. One thing I don't like about your mixin approach is the implicit and unenforced assumption that the target of the mixin has creator and updater properties

Personally, I would probably just use plain-old inheritance for this, e.g.

abstract class Audit {

    String creator
    String updater

    def beforeInsert() {
        this.creator = 'foo'
        this.updater = 'foo'
    }

    def beforeUpdate() {
        this.updater = 'bar'
    }

    static constraints = {
        creator nullable: false
        updater nullable: false
    }
}

any domain classes that need to be audited would simply extend Audit. An alternative (and preferable) approach would be to use a trait rather than an abstract base class, but you'll need to be using a fairly recent Grails version in order to do this.

Instead of mixins you can use the Event Bus of the Grails Platform plugin to make your app more DRY. The plugin supports adding listeners to GORM events and they can be applied to any given class or interface instance. You can also attach more than one listener and write more concise unit tests.

If you want to share some logic accross domains, they must implement an interface and then create a service with the following method:

// domainService.groovy

@grails.events.Listener(namespace='gorm')
def beforeInsert(DomainInterface domain){
    domain.creator = 'foo'
    domain.updater = 'bar'

    // If the method returns false, then domain.save() won't be called. 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!