9

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?

12
  • 3
    Saving a map as a string doesn't sound sensible at all. Have you heard of data normalization?
    – Niklas B.
    Apr 21, 2012 at 8:41
  • Sorry, I write this question in wrong manner, now it's fixed, I mean keys and it's values. Apr 21, 2012 at 9:11
  • You can just use toString() on both the keys and values. What's the problem?
    – Niklas B.
    Apr 21, 2012 at 9:14
  • 1
    I don't thik so that this is the very basic stuff, look at this post: forum.hibernate.org/viewtopic.php?f=1&t=999270&start=0 Maybe you should consult a Java beginners book. Apr 21, 2012 at 9:30
  • @Niklas B. Before you write something and someone recommended that he should read something, think twice! If you really don't understand a problem and don't know the specific solution, please don't spam questions with your irrelevant comments and try to study somethink before you post your answer. Apr 21, 2012 at 11:00

2 Answers 2

3

@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)
)
1
  • Thanks for your post, I tried it, but didn't help me. I use postgresql db and hibernate create int8, bytea, bytea data types in table. Apr 21, 2012 at 10:37
1

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?

1
  • Yes, it's the keys and it's values, Sorry I'm starting with JPA2 and hibernate, can you post the here the changes in code which must I do to store this keys and values as String? Apr 21, 2012 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.