Grails一行(缩写)属性约束定义是可能的



如果我有一个类的许多属性共享相同的属性约束,像这样:

class myClass {
    String thisString
    String thatString
    String theOtherString
    static constraints = {
        thisString(nullable: true)
        thatString(nullable: true)
        theOtherString(nullable: true)
    }
}

是否有更简单的"一行"方式来声明静态约束?类似于说:

static constraints = {
    thisString, thatString, theOtherString(nullable:true)
}

?谢谢你。

Grails有一些被称为全局约束的东西。这允许您在许多不同的GORM对象之间重用相同的约束。

grails-app/conf/Config.groovy

grails.gorm.default.constraints = {
    mySharedConstraint(nullable:true, ...)
}

myClass.groovy

class myClass {
    String thisString
    String thatString
    String theOtherString
    static constraints = {
        thisString(shared: mySharedConstraint)
        thatString(shared: mySharedConstraint)
        theOtherString(shared: mySharedConstraint)
    }
}

如果你甚至不想去…您可以简单地将约束应用于所有内容,方法如下:

grails.gorm.default.constaints = {
    '*'(nullable:true)
}

start将应用于所有属性。

最后,我会参考上面的链接。好运!

最新更新