简体   繁体   English

如何使用Enum作为hibernate中的值来注释EnumMap?

[英]How to annotate an EnumMap with an Enum as a value in hibernate?

I'm using Hibernate annotations in a class containing a map of properties, which are basically <name, value> pairs. 我在包含属性映射的类中使用Hibernate注释,这些属性基本上是<name, value>对。 The property names are defined in a PROPERTY enum , and each property has a set of permissible values, also defined as an enum . 属性名称在PROPERTY enum中定义,每个属性都有一组允许值,也定义为enum Since each property has its own enum defined for its values, the property map is defined as 由于每个属性都为其值定义了自己的enum ,因此属性映射定义为

Map<PROPERTY, Enum> properties = new EnumMap<PROPERTY, Enum> (PROPERTY.class);

I am having trouble mapping the Enum value. 我无法映射Enum值。 This definition: 这个定义:

@ElementCollection
@MapKeyEnumerated(EnumType.STRING)
@MapKeyColumn(name="name")
@Column(name="value")
@Enumerated(EnumType.STRING)
Map<PROPERTY, Enum> properties = new EnumMap<PROPERTY, Enum> (PROPERTY.class);

generates the following DDL: 生成以下DDL:

create table EnumMapTest (
    id bigint not null auto_increment,
    primary key (id)
) ENGINE=InnoDB;

create table EnumMapTest_properties (
    EnumMapTest_id bigint not null,
    value tinyblob,
    name varchar(255) not null,
    primary key (EnumMapTest_id, name)
) ENGINE=InnoDB;

As you can see, the Enum class is mapped as a tinyblob , which is totally unreadable in the database. 如您所见,Enum类被映射为tinyblob ,在数据库中完全不可读。

If I define the map with a concrete enum 如果我用具体的enum定义地图

enum VALUE {ONE, TWO, THREE};

@ElementCollection
@MapKeyEnumerated(EnumType.STRING)
@MapKeyColumn(name="name")
@Column(name="value")
@Enumerated(EnumType.STRING)
Map<PROPERTY, VALUE> properties = new EnumMap<PROPERTY, VALUE> (PROPERTY.class);

the mapping is fine: 映射很好:

create table EnumMapTest_properties (
    EnumMapTest_id bigint not null,
    value varchar(255),
    name varchar(255) not null,
    primary key (EnumMapTest_id, name)
) ENGINE=InnoDB;

So the issue is the mapping of the Enum class itself. 所以问题是Enum类本身的映射。

Is there a way to do map an Enum to something readable (preferably a string) without creating a custom type? 有没有办法在不创建自定义类型的情况下将Enum映射到可读的内容(最好是字符串)?

I hope the fact that we are still at Hibernate 3.6.10 won't be held against us. 我希望我们仍然在Hibernate 3.6.10这一事实不会被我们拒之门外。

TIA for any assistance TIA提供任何帮助

If you don't specify any type, hibernate saves it using serialization. 如果您没有指定任何类型,则hibernate使用序列化保存它。 That's why it generates a tinyblob. 这就是为什么它会产生一个小小的怪物。

In your case, I would recommend that you make a Map of strings ( Map<PROPERTY, String> ) since you just use Enum values. 在您的情况下,我建议您创建一个字符串Map<PROPERTY, String>Map<PROPERTY, String> ),因为您只使用Enum值。 You have to convert the enums to string by hand (combination of enum-class name and enum-name) but it's readable. 您必须手动将枚举转换为字符串(enum-class name和enum-name的组合),但它是可读的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM