常见域列的Mixin常见的beforeInsert和beforeUpdate方法

jon*_*bot 1 grails groovy grails-orm mixins

我们公司使用的大多数域对象都有一些共同的属性.它们代表创建对象的用户,最后更新对象的用户以及用于执行此操作的程序.

在利益DRY荷兰国际集团我的领域类,我想找到一些方法来添加相同beforeInsert和更新前的逻辑具有这些列的所有领域类不与那些不干扰.

我是怎么想这样做的,就是使用一个带有自己的beforeInsert和beforeUpdate方法的Mixin.我知道你可以在域类上使用Mixins.

package my.com

import my.com.DomainMixin

@Mixin(DomainMixin)
class MyClass {
    String foo
    String creator
    String updater

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


package my.com
class DomainMixin {
    def beforeInsert() {
        this.creator = 'foo'
        this.updater = 'foo'
    }

    def beforeUpdate() {
        this.updater = 'bar'
    }
}
Run Code Online (Sandbox Code Playgroud)

单元测试表明,当以这种方式实现时,beforeInsert方法实际上没有被触发.

旁注:我也知道可以使用metaClass 在BootStrap.groovy文件中添加方法,但我的好奇心已经变得更好了,我真的想看看mixin是否有效.请随意告诉我,这是更好的方法,我不应该混淆男人不应该的地方.

Dón*_*nal 5

仅供参考,groovy.lang.Mixin强烈建议不要使用(由Groovy项目负责人提供).如果你必须使用mixins,你应该使用grails.util.Mixin.我不喜欢你的mixin方法的一件事是隐含和未强制的假设,即mixin的目标有creatorupdater属性

就个人而言,我可能只是使用普通的继承,例如

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
    }
}
Run Code Online (Sandbox Code Playgroud)

任何需要审计的域类都会扩展Audit.另一种(也是更好的)方法是使用特征而不是抽象基类,但是为了做到这一点,你需要使用相当新的Grails版本.