如何"inherit" trait 的约束?
How to "inherit" constraints from trait?
我有一个特征和以下域 classes:
trait Named {
String name
static constraints = {
name blank:false, unique:true
}
}
@Entity
class Person implements Named {
String fullName
static constraints = {
fullName nullable:true
}
}
@Entity
class Category implements Named {
}
在此设置中,Named.constraints 在 Category
上工作正常,但在 Person
上被忽略。
如何在实施域 class 的 constraints
块中包含来自特征的约束?
How can I include the constrains from a trait in a constraints block
of an implementing domain class?
框架不支持
我找到了重用约束最不痛苦的方法。
我添加了一个新的class:
class CommonConstraints {
static name = {
name blank:false, unique:true
}
}
然后我用一些 groovy 魔法代替 importFrom Named
,但它不起作用:
@Entity
class Person implements Named {
String imgUrl
String fullName
static constraints = {
CommonConstraints.name.delegate = delegate
CommonConstraints.name()
fullName blank:false, unique:true
imgUrl url:true
}
}
而且效果很好。
是的,解决方案与 inheritance/implementation 模型不一致,但完成了代码重用工作。
对于不那么棘手的情况,域 class 没有自己的约束,将使用特征中的约束,就像我原来的问题一样。
我有一个特征和以下域 classes:
trait Named {
String name
static constraints = {
name blank:false, unique:true
}
}
@Entity
class Person implements Named {
String fullName
static constraints = {
fullName nullable:true
}
}
@Entity
class Category implements Named {
}
在此设置中,Named.constraints 在 Category
上工作正常,但在 Person
上被忽略。
如何在实施域 class 的 constraints
块中包含来自特征的约束?
How can I include the constrains from a trait in a constraints block of an implementing domain class?
框架不支持
我找到了重用约束最不痛苦的方法。
我添加了一个新的class:
class CommonConstraints {
static name = {
name blank:false, unique:true
}
}
然后我用一些 groovy 魔法代替 importFrom Named
,但它不起作用:
@Entity
class Person implements Named {
String imgUrl
String fullName
static constraints = {
CommonConstraints.name.delegate = delegate
CommonConstraints.name()
fullName blank:false, unique:true
imgUrl url:true
}
}
而且效果很好。
是的,解决方案与 inheritance/implementation 模型不一致,但完成了代码重用工作。
对于不那么棘手的情况,域 class 没有自己的约束,将使用特征中的约束,就像我原来的问题一样。