views:

593

answers:

1

Hi all,

My entity defines a field like

Map<String, String> props;

I've got this hibernate xml configuration

<map name="props" table="PROPS">  
    <key column="id"/>  
    <index column="name" type="string"/>  
    <element column="value" type="string"/>  
</map>

Now I want my Map to be an EnumMap like

Map<MyEnum, String> props;

I think I need to create my own Hibernate UserType for MyEnum and then reference this from the hbm.xml ...
Do you have any idea of what's the best/easiest way to achieve this?
Thanks a lot

+1  A: 

Hibernate already has an Enum type. It's part of Hibernate Annotations distribution rather than Hibernate Core, however you can very much use it with XML mappings by specifying the type explicitly:

<property name="myEnum" type="org.hibernate.type.EnumType"/>

I haven't tried to specify Enum as map key, to be honest - I don't see why it wouldn't work, but Hibernate documentation says that map key can be of "basic" type and it's possible that EnumType will not qualify.

Note, however, that your Map will NOT be an EnumMap when it's loaded from the database. Hibernate returns collections as its own types that implemented corresponding interfaces (e.g. Map / Set / List ...). If it's critical for you to have your Map as EnumMap (which it shouldn't be - other than minor performance improvement there should be no difference) than you will have to write a custom type - for Map itself, rather than Enum. It's rather hard, because for collections it would have to be dereferenceable in queries - I would strongly advice against going this route.

ChssPly76