Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA relations and polymorphism

I have the following class structure (details are omitted for clarity):

For example:

@Entity
class A{

@OneToMany
private List<B> b;

@OneToOne
private C c;


}

interface B {

}

@Entity
@Inheritance
abstract class Babstract implements B {

}

@Entity
@PrimaryKeyJoinColumn
class B1impl extends Babstract  {

}

@Entity
@PrimaryKeyJoinColumn
class B2Impl extends Babstract {

}

I want to load all B's belonging to C. Class A relates B to C. B and C are unaware of each others existence and I like to keep it that way. I don't know the actual implementing type of B and I don't really care because I use the abstract data type B (the interface). The implementation can vary over time, for example, a new implementation of B can be added in the future in a new release.

Is this possible with JPA and how do I do that? I can't use the targetEntity attribute, if I'm correct, because I don't know the implementing class and I don't care. B is polymorph.


2 Answers

JPA doesnt work well with interfaces. You need to make B at least an abstract class with the entity annotation. You can make B a totally empty abstract class (except an id field, you need that) and then add inheritance. The reason for this is that in order for an entity to have a reference to another entity, there must be a way to reference that entity in the database - and if there is no table for B then there is no way to do that.

like image 163
Piotr Avatar answered Aug 23 '26 16:08

Piotr


JPA does not have interface support, but some JPA providers do. If using EclipseLink you can use a @VariableOneToOne mapping to map to an interface.

Now, if the B interface only has one current implementer, and this is just a "some possible time in the future", then I would just set the targetEntity to Babstract. If "some possible time in the future" actually does occur (probably will not), then you can change the mappings then.

See, http://en.wikibooks.org/wiki/Java_Persistence/Advanced_Topics#Interfaces

like image 35
James Avatar answered Aug 23 '26 15:08

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!