Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define polymorphism in JPA

there is a situation. For example, I am designing simple blog. There are articles and photographies. Users can add their comment to both of them. So when I write it in Java, it looks like this:

public interface Commentable { ... }

public class Article implements Commentable { ... }

public class Photo implements Commentable { ... }

public class Comment { 
   ...
   private Commentable commentTo; 
}

This is clear and I hope that design is correct. But now I would like to persist it in database and I want to use JPA annotations. Primarily I have to use JPA 1.0 but if there is not solution I would like to know how to do it in JPA 2.0. I found out that there is a way with classic inheritance but I think that Commentable shouldn't be a parent of these object, it is only extension in light of design.

Is there any way how to persist it without changing of desing, please? Thanks a lot

like image 740
Gaim Avatar asked Oct 28 '10 15:10

Gaim


1 Answers

Is there any way how to persist it without changing of design, please? Thanks a lot

JPA doesn't really support your design (to be precise, you can map a relation pointing to an interface if there is a single implementation, but that's not your case). Your JPA provider might have some support for this though (e.g. EclipseLink has a @VariableOneToOne annotation).

With standard JPA, the usual approach would be to use an abstract class (with or without your interface) and to use inheritance. For example (keeping the interface):

public class Comment { 
   ...
   @OneToOne(targetEntity=MyAbstractBaseClass.class)
   private Commentable commentTo; 
}

Where both Article and Photo would extend MyAbstractBaseClass and implment the interface.

The JPA wikibook has two good sections on this topic, see below.

Resources

  • JPA Wikibook:
    • My relationship target is an interface
    • Variable and Heterogeneous Relationships
like image 141
Pascal Thivent Avatar answered Oct 12 '22 08:10

Pascal Thivent