Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store Map<Enum, Enum> as String

I need help with storing a map in JPA2, where both keys and values are enums (Map<Enum, Enum>). With Hibernate as my JPA provider it stores the enums as a blob but I need the data stored as strings. I tried the following annotations to fix this problem:

@ElementCollection(fetch = FetchType.EAGER)
@MapKeyEnumerated(value = EnumType.STRING)
public Map<Enum, Enum> getElementsMap() {
    return elementsMap;
}

But the data is still being stored into the DB as blob. Has anyone solved this problem?

like image 935
user1289877 Avatar asked Apr 21 '12 08:04

user1289877


People also ask

Can we convert enum to String?

We can convert an enum to string by calling the ToString() method of an Enum.

Can I use enum as map key?

EnumMap is a specialized map implementation that uses only Enum type key. In HashMap, we can use Enum as well as any other object as a key.

Can you map enum?

Since a JavaScript enum is just an object, you can iterate over an object using map() and Object.

How do you map a String to an enum?

You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.


2 Answers

@Enumerated is used to to define type for value. Following maps to table where column for both key and value are varchars and name of the enum will be saved:

@Enumerated(EnumType.STRING)
@ElementCollection(fetch = FetchType.EAGER)
@MapKeyEnumerated(value = EnumType.STRING)
public Map<MyEnum, MyOtherEnum> elementsMap = new HashMap<>();

It will produce roughly following table:

[NAME_OF_ENTITY]_ELEMENTSMAP (
  NAME_OF_ENTITY_ID INTEGER, 
  ELEMENTSMAP VARCHAR(255), 
  ELEMENTSMAP_KEY VARCHAR(255)
)
like image 119
Mikko Maunu Avatar answered Sep 26 '22 17:09

Mikko Maunu


Almost each and every Java Object has a toString() method If you want to represent your Map in the database, then I suggest this be your option.

However I have to ask are you sure it is the MAP you wish to store and not the elements of the keys or values?

like image 43
thejartender Avatar answered Sep 26 '22 17:09

thejartender