Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA polymorphism association with multiple tables

Is it possible for an entity to have an One to One polymorphism association to multiple tables. Let say an entity has 2 specific columns which are used to :

link_type - column that identify which table should associate to

link_id - column that define the foreign key of the table once the table was identified.

like image 838
kenn3th Avatar asked Oct 02 '13 06:10

kenn3th


2 Answers

I think you mean inheritance mapping for polymorphic association.

Entity Inheritance

JPA has a powerful feature called entity inheritance similar to class inheritance in java. Entity classes can extend non-entity classes, and non-entity classes can extend entity classes. Entity classes can be both abstract and concrete.

Inheritance Strategies

There are 3 inheritance strategies

  • The Table per Concrete Class Strategy
  • The Joined Subclass Strategy
  • Single Table Strategy

The Table per Concrete Class Strategy

The table per concrete class inheritance mapping strategy is based on separate tables mapped for each entity. Each class has its own table in the DB while entity classes is inherited from a base class. Difference in this strategy is tables are not logically separated. There still exists a inheritance between them.

The Joined Subclass Strategy

Joined table inheritance mapping strategy is based on separate tables joined to base table. There are classes which are inherited from a base class and data table are also have same scheme which is linked to each other using foreign keys.

Single Table Strategy

JPA mappings has a powerful feature called inheritance mapping. It has a similar concept in JPA as in OOP concept. Tables and mappings are inherited base classes or tables. There are 3 types of mapping strategies and one is called single table mapping.

You can see detailed explanation of all these in my tutorials. Please look at them.

See also

JPA Tutorial

Hibernate Reference

like image 158
erencan Avatar answered Oct 01 '22 23:10

erencan


I think I have found a solution by using @Any or @ManyToAny annotation. Those are not standard JPA annotation but hibernate specific annotation.

like image 44
kenn3th Avatar answered Oct 01 '22 23:10

kenn3th