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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With