I have a trait and the following domain 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 {
}
In this setup the Named.constraints are working fine for Category
, but are ignored for Person
.
How can I include the constrains from a trait in a constraints
block of an implementing domain class?
I found the least painful way to re-use the constraints.
I added a new class:
class CommonConstraints {
static name = {
name blank:false, unique:true
}
}
Then instead of importFrom Named
which didn't work, I sprinkle some groovy magic:
@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
}
}
And it works like charm.
Yes, the solution not consistent with inheritance/implementation model, but gets the job of code reuse done.
For the less tricky cases, where the domain class does not have it's own constraints, the ones from a trait will be used, like in my original question.