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?
We can convert an enum to string by calling the ToString() method of an Enum.
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.
Since a JavaScript enum is just an object, you can iterate over an object using map() and Object.
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.
@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)
)
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With