问题描述
在Grails中,有没有办法限制枚举映射到的列的大小。在下面的例子中,我希望列类型为char(2)enum FooStatus {
pre>
BAR( 'br'),TAR('tr')
final static String id
}
$ b $ class Foo {
FooStatus status
static constraints = {
status(inList:FooStatus.values()* .id,size:2..2)
}
}
在导出模式时,inList和size都不起作用,列类型保持默认值(varch(255))
也许我可以这样做,如果我定义一个新的UserType。任何想法?
谢谢您
-ken解决方案考虑到枚举在GORM内部映射的方式,我认为这是不可能的。但将代码更改为这样:
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 {
字符串状态
FooStatus getFooStatus(){status ? FooStatus.byId(status):null}
void setFooStatus(FooStatus fooStatus){status = fooStatus.id}
static transients = ['fooStatus']
静态约束= {
status inList:FooStatus.values()* .id
}
static mapping = {
status sqlType:'char(2)'
$ / code>
添加瞬态获取器和设置器允许您设置或获取String(id)或枚举值。
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) } }
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 ?
Thank you-ken
解决方案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 } } }
and
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)' } }
Adding the transient getter and setter allows you to set or get either the String (id) or enum value.
这篇关于Grails枚举映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!