1

在完成问题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 的枚举(如上所示)?

4

2 回答 2

1

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

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

于 2015-01-14T04:15:13.373 回答
1

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

您引用的问题是指使用Enum 类的内置序数值,而不是属性值。您想要的是自定义类型编组器(或者可能是子类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。

于 2015-01-14T02:24:50.237 回答