问题描述
在 Grails 中,有没有办法限制枚举映射到的列的大小.在以下示例中,我希望列类型为 char(2)
in Grails, Is there a way to limit the size of the column to which the enum is mapped. In the following example, i would like the column type to be char(2)
enum FooStatus {
BAR('br'), TAR('tr')
final static String id
}
class Foo {
FooStatus status
static constraints = {
status(inList:FooStatus.values()*.id,size:2..2)
}
}
导出schema时inList和size都没有任何影响,列类型保持默认值(varch(255))如果我定义一个新的 UserType,也许我可以做到这一点.有什么想法吗?
both inList and size do not have any effect when exporting the schema, the column type keeps its default value (varch(255))Maybe i could do that if i define a new UserType. Any idea ?
谢谢-ken
推荐答案
鉴于枚举在 GORM 中的内部映射方式,我认为这不是直接可行的.但是将代码更改为此有效:
I don't think it's directly possible given the way enums are mapped internally in GORM. But changing the code to this works:
enum FooStatus {
BAR('br'),
TAR('tr')
private FooStatus(String id) { this.id = id }
final String id
static FooStatus byId(String id) {
values().find { it.id == id }
}
}
和
class Foo {
String status
FooStatus getFooStatus() { status ? FooStatus.byId(status) : null }
void setFooStatus(FooStatus fooStatus) { status = fooStatus.id }
static transients = ['fooStatus']
static constraints = {
status inList: FooStatus.values()*.id
}
static mapping = {
status sqlType: 'char(2)'
}
}
添加瞬态 getter 和 setter 允许您设置或获取字符串 (id) 或枚举值.
Adding the transient getter and setter allows you to set or get either the String (id) or enum value.
这篇关于Grails 枚举映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!