daly
daly

Reputation: 43

JPA 2 and generic classes

in my Data Model I need to have a generic Table "DICTIONNARY" that store all values in the data base like this :

TYP         KEY          VALUE
---------------------------------
COUNTRY     TUN          TUNISIA
COUNTRY     FRA          FRANCE
PROFESSION  LAW          Lawyer
PROFESSION  FRA          Farmer

and there is other tables that can references the generic table like table Person

CODE        NAME         COUNTRY          PROFESSION
-----------------------------------------------------
1           PAUL         TUN              FRA      
2           Armin        FRA              DOC

the colomn Person.country just references the column dicionnary.key where typ='COUNTRY' and Person.profession just references the column dictionnary.key where typ='PROFESSION'

is there any solution to make that DataModel with JPA 2.

Thanks in advance !!

Upvotes: 0

Views: 186

Answers (1)

SJuan76
SJuan76

Reputation: 24885

Depends of what you mean by solution. I do not think that there is a way to map two entities to the same table, unless if you use inheritance.

So the options are:

  • Use inheritance and make the entities of Country and Profession related. Check @DiscriminatorColumn and @DiscriminatorValue. More info here.

  • Use a "generic" entity with a composite key (@IdClass). It will be your code that will interpret the attribute retrieved as either possibility.

  • FIX YOUR DATA MODEL. Mixing unrelated items in the same table goes against normalized design and will create issues using other database tools (like foreign keys). Create a table for countries and another for professions. This is the approach that I advise.

Upvotes: 1

Related Questions