I'd like to use polymorphism with relationship in a JPA enabled J2SE application.
On one hand I've got the Customer and Supplier classes that both extends Partner.
On the other hand, I've got CustomerOrder and SupplierOrder that both extends Order.
I've simplified the example for clarity but the code snippets below should clarify what annotations have been used to map these POJOs to the database tables.
The Customer and Supplier map to different tables whereas both types of Order are stored in the same table with a discriminator field.
The idea is to add a one-to-one relationship between:
- a Customer and CustomerOrder and
- a Supplier and a SupplierOrder
But it would be nice to define the relationship in Order so that one Order has one Partner and let Order subclasses define the concrete entity to use.
The 'order' table posseses two fields, 'customer_id' and 'supplier_id' which contain the appropriate identifier to use for the relationships.
I was wondering if it could be possible to define the relationship in the Order class with something like :
and let subclasses define the partner field / relationship with something like :
@AttributeOverride(name = "partner", column = @Column(name = "customer_id")) for CustomerOrder and
@AttributeOverride(name = "partner", column = @Column(name = "supplier_id")) for SupplierOrder
I already tried but doesn't seem to work . I still don't know how to specify which Partner concrete subclass to use with annotation (is it possible by the way ?).
Any idea how I should fix this ?
Joined: Oct 01, 2007
You are probably best off define the OneToMany in the Order subclasses, to the Customer or Supplier directly.
JPA does not allow a relationship to a MappedSuperclass.
You could change Partner to an Entity, and use JOINED or TABLE_PER_CLASS inheritance, then you could define the OneToMany in Order to Partner, but mapping the relationship in the subclasses would be more efficient.
You could also try defining the relationship to Partner in Order, then overriding it in the subclasses entirely (i.e. define getPartners() in subclasses as well). This may work depending on your JPA provider, but is probably not kosher.