14

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

错误

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}"
    }
}
4

1 回答 1

25

看看这里...

Grails 枚举映射

Grails GORM 和枚举

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

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

static mapping = {
    someEnum enumType:"ordinal"
}
于 2012-08-21T00:04:41.123 回答