使用grails mongodb中的自定义ID保存枚举

时间:2014-05-27 11:48:58

标签: grails grails-2.3

我错误地认为在完成问题https://jira.grails.org/browse/GPMONGODB-232之后将枚举类型保存为序数值,我们现在可以使用自定义ID保存枚举。

例如:

这不会保存字段类型,值为2或3。

package test

class User {

    static mapping = {
        //type enumType: "ordinal"
    }

    UserType type

    String name
}

enum UserType {
    A(2),
    B(3),

    int getId() {
        this.id
    }

    final int id
    UserType(int id) {
        this.id = id
    }
}

如何在安装了mongodb插件的grails应用中使用自定义ID(如上所示)保存枚举?

2 个答案:

答案 0 :(得分:1)

我还没有检查过Grails 2.4,但是在2.3.8(或者至少在grails-datastore-core 3.1.0中)你不能。

您引用的问题涉及使用Enum类的built-in ordinal value,而不是属性值。你想要的是一个custom type marshaller(或者可能是子类AbstractMappingAwareCustomTypeMarshaller)。不幸的是,在考虑自定义类型映射器之前,Grails会检查属性是否为枚举。来自org.grails.datastore.mapping.model.config.GormMappingConfigurationStrategy#getPersistentProperties():

else if (Enum.class.isAssignableFrom(currentPropType) ||
       propertyFactory.isSimpleType(propertyType)) {
    persistentProperties.add(propertyFactory.createSimple(entity, context, descriptor));
}
else if (MappingFactory.isCustomType(propertyType)) {
    persistentProperties.add(propertyFactory.createCustom(entity, context, descriptor));
}

我说这是一个错误,如果它仍然存在于2.4.4(或者目前最新的版本),那么它应该报告给Grails。

答案 1 :(得分:1)

如果有人需要此功能,请回答我自己的问题。现在,mongodb还支持使用自定义ID保存枚举,如问题中所述。

所需的更改已经被拉取请求https://github.com/grails/grails-data-mapping/pull/41合并,他们只需要发布新版本的mongodb或GORM。