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

请您参考如下方法:

我还没有检查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。


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!