grails - Grails 域中的枚举

标签 grails groovy

我正在尝试使用 enum在 Grails 2.1 域类中。我正在通过 grails generate-all <domain class> 生成 Controller 和 View 命令,当我访问 View 时,出现如下所示的错误。我在这里缺少什么?

错误

Failed to convert property value of type java.lang.String to required type 
com.domain.ActionEnum for property action; nested exception is 
java.lang.IllegalStateException: Cannot convert value of type 
[java.lang.String] to required type [com.domain.ActionEnum] for property action: 
no matching editors or conversion strategy found

枚举 (在 /src/groovy 中)
package com.domain

enum ActionEnum  {
    PRE_REGISTER(0), PURCHASE(2)

    private final int val
    public ActionEnum(int val) {
        this.val = val
    }

    int value() { return value }
}

域名
package com.domain

class Stat {
    ActionEnum action

    static mapping = {
        version false
    }
}   

查看
<g:select name="action" 
    from="${com.domain.ActionEnum?.values()}"
    keys="${com.domain.ActionEnum.values()*.name()}" required="" 
    value="${xyzInstance?.action?.name()}"/>

编辑

现在出现错误 Property action must be a valid number更改以下内容后。

查看
<g:select optionKey='id' name="action" 
from="${com.domain.ActionEnum?.values()}" 
required="" 
value="${xyzInstance?.action}"/>  // I tried simply putting a number here

枚举
package com.domain

enum ActionEnum  {
    PRE_REGISTER(0), PURCHASE(2)

    final int id
    public ActionEnum(int id) {
        this.id = id
    }

    int value() { return value }

    static ActionEnum byId(int id) {
        values().find { it.id == id }
    } 
}

域名
package com.domain.site

class Stat {
    static belongsTo = Game;

    Game game
    Integer action

    static mapping = {
        version false
   }

    static constraints = {
        action inList: ActionEnum.values()*.id
    }

    String toString() {
        return "${action}"
    }
}

最佳答案

看看这里...

Grails Enum Mapping

Grails GORM & Enums

你也可能会遇到这个问题。从文档:

1) 枚举类型现在使用它们的字符串值而不是序数值进行映射。您可以通过如下更改映射来恢复旧行为:

static mapping = {
    someEnum enumType:"ordinal"
}

关于grails - Grails 域中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12046624/

相关文章:

grails - GORM不会在两个类之间的一对多关系中创建表

grails - 如何嵌套Grails Controller 路径

groovy - 安装 Groovy

grails - 从grails 2.3.4迁移到3.3.8时无法模拟域

hibernate - Grails - 如何在服务中保存域对象?

java - mock groovy new File.eachFile()

json - 在 Groovy 中获取具有随机名称的单个节点的 JSON 子节点

eclipse - eclipse 无法设置断点

java - 使用 groovy 的 toURL 方法忽略 SSL 错误

grails - 如何避免 grails 中的额外参数(GSP 页面到 Controller )