Hibernate how to implement dynamic data structure

data-structures, hibernate, orm

Solution

Hibernate Dynamic mappings are the recommended solution for this use case. With dynamic Hibernate mappings everything gets mapped into Java Maps where keys are strings and values are types such as String, Integer, etc. or other maps.

So in the case of your example you would get a map with two entries with keys "Birds" and "Mammals" that themselves would be maps.

Mammals value would be a map with 3 entries "Dog", "Cat" and "Horse". The "Cat" value would be a map with two entries: "vaccinations" and "visit record", etc.

Dynamic mappings can be used together with the more frequently used static mappings.

The dynamic mappings are not the most frequently used feature of Hibernate, but they are stable since a long time and they are made preciselly for this use case.

Problem

I have this massive data structure - I would like to avoid specifying class for each type... Using hibernate, can this structure be implemented in such way that when adding new species or foreign key - no recompilation will be needed? ``` Animal | Birds | Parakeet | Love Bird -> [one to many:visit record] | Budgerigar -> [one to many:visit record] Mammals | Dog -> [one to many:vaccinations] [one to many:visit record] [one to many:Haircuts] | Cat -> [one to many:vaccinations] [one to many:visit record] | Horse -> [one to many:vaccinations] [one to many:Horse breeding] Tree is about 100+ types of animals ``` So for example - Example1:I can add additional type without recompiling the code ``` | Cow -> [one to many:vaccinations] -> [one to many:pregnancy dates] ``` Example2: ability to Create dynamic links between entities ``` | Horse -> [one to many:vaccinations] [one to many:Horse breeding] LinkToOwner-> [one to one: owner] ```

Original source