Interface Handling Using ORM in Java

I want whether it is possible to handle the connection with abstract Entity (ie: Interface ) in another Entity. eg:
I have a class called Foo , which has a bar attribute, which is of type bar , which is an interface . Several classes ( Bar1 , Bar2 ) implement bar and everything is also persistable .

 class Foo{ Bar bar; // this will be either Bar1 or Bar2 } interface Bar{ // some methods } class Bar1 implements Bar{ String s; // Bar1 and Bar2 have different represantations ,hence they must be persisted to different tables } class Bar2 implements Bar{ int i; } 

Now, how can I handle this with ORM in Java? ie: so when I retrieve Foo , it bar is an instance of one of the bar implementations.

+6
source share
2 answers

Yes, you can support polymorphic associations, but you need to make the Bar abstract base @Entity class instead of interface , since JPA does not work with interfaces, for example:

 @Entity @Inheritance(strategy = InheritanceType.JOINED) public abstract class Bar { ... } @Entity public class Bar1 extends Bar { private String s; ... } @Entity public class Bar2 extends Bar { private int i; ... } 

If you model it this way, you can query for Bar instances polymorphically using JP-QL, for example. select b from Bar .

Link:

https://docs.oracle.com/javaee/7/tutorial/persistence-intro002.htm#BNBQN

+4
source

Associated with ck1's answer, but with one table.

Using InheritanceType.JOINED requires a table for the base class and one table for each subclass. If you use InheritanceType.SINGLE_TABLE with DiscriminatorColumn , you can store all your objects in one table and still extract them from one collection. You can also combine DiscriminatorColumn with InheritanceType.JOINED if you want to find out what type of object is in the base class by storing separate subclass fields in separate tables.

 @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "DISC") public abstract class Bar { ... } @Entity @DiscriminatorValue("BAR1") public class Bar1 extends Bar { ... } @Entity @DiscriminatorValue("BAR2") public class Bar2 extends Bar { ... } 
+1
source

All Articles