All is in the question. How to map a Map with Hibernate using annotations ? And what's the associated database structure ?
Asked
Active
Viewed 2,251 times
1 Answers
2
You are probably looking for a generic key-value database structure where values can have multiple types. This is typically resolved by having some sort of abstract Value
class with key attribute and several subclasses, each for every desired type:
Now you use:
Map<String, Value>
Of course this approach has many disadvantages, correctly choosing inheritance strategy being one of them (it depends on how many different types you want to store). But at least it is perfectly type-safe.
I don't have any experience with NHibernate, but with Hibernate (see: How do you map a "Map" in hibernate using annotations?) you can map Map
directly.

Community
- 1
- 1

Tomasz Nurkiewicz
- 334,321
- 69
- 703
- 674
-
It's what I was thinking of... In my case I would like to add new subclass easily (in fact without creating a new subclass with all hibernate annotations). Actually, to simulate this, I serialize in json the hashtable and save it in one big text field of my class... But this is not very clean ;) Thanks for your answer – Jerome Cance Aug 10 '11 at 08:05
-
Of course, you can even rely on Hibernate and simply serialize objects in BLOBs... But suggested approach actually allows you to query the values using SQL (at least primitives). If you need so flexible schema, maybe document oriented database (like MongoDB) would be a better tool? – Tomasz Nurkiewicz Aug 10 '11 at 08:08
-
This is just that part which need to be flexible, so using mongodb for only that can be overkill... But no matter, I think I will use the schema you propose. – Jerome Cance Aug 10 '11 at 08:33