fledglingCoder
fledglingCoder

Reputation: 398

Is there a way to override ID in an entity's subclass in JPA?

Under a specific requirement such as not using an abstract base class (or super class), I need to implement a simple hierarchy of two entities one of which is supposed to extend the other but have a different @Id of its own.

My googling about this seems to conclude this is impossible or only on condition that I use a mapped super class (which is forbidden in my case due to a certain policy).

I don't want to duplicate the code of the entity with several dozen attributes and then mutate the duplicate by adding / overriding attributes in order to avoid future maintenance problems, but then I'm stuck in JPA restrictions.

Any help / suggestion will be appreciated.

Upvotes: 2

Views: 3108

Answers (1)

kostja
kostja

Reputation: 61538

Having different id types for non-abstract derived entities is not compatible with the JPA inheritance strategies.

What I mean is:

Imagine you have succeeded and different classes in the hierarchy use different incompatible types for the id.

  • how would you define the DB constraints for a single table inheritance in such a case?
  • and for joined inheritance?

EDIT: JPA does not distinguish between inheritance strategies when it comes to id definition. And you cannot even be sure that you can use TABLE_PER_CLASS with pure JPA. Virtually all providers implement it, but it is specified as optional and thus the least portable inheritance strategy.

The question remains however. How can the DB constraints look in order to make the table usable unambiguously by the persistence provider? E.g. Which columns should comprise the primary key on DB level?

If you cannot make the parent entity neither abstract nor embeddable nor use the same id, you will have to work around that. How you do that is highly dependant on what you want to achieve and what organizational constraints you have.

There are several possibilities - the least invasive would be composition, having A as a field in B, effectively creating a 1-1 relation.

More ugly approaches could be native and constructor queries but I doubt you want to descend that far.

tl;dr No, it is not possible.

Upvotes: 3

Related Questions