JPA: Implementing Model Hierarchy - @MappedSuperclass vs. @Inheritance

huzeyfe picture huzeyfe · Mar 12, 2012 · Viewed 32.4k times · Source

I am using Play Framework 1.2.4 with PostgreSQL and JPA. I would like to have a Model hierarchy and see that there are some alternatives to doing this.

I have a base class (which is abstract) and two concrete classes extending this base class. I don't want to persist this base class while I want to have concrete classes. In the base class, I have another Model classes as properties, in other words, I have @ManyToOne relationships in my base class.

My question is what is the best way of implementing this? Using @MappedSuperclass or @Inheritance with TABLE_PER_CLASS strategy? I am a bit confused as they seem virtually equivalent.

I also have some concerns about querying and performance issues that I might face in future.

Answer

JB Nizet picture JB Nizet · Mar 12, 2012

MappedSuperClass must be used to inherit properties, associations, and methods.

Entity inheritance must be used when you have an entity, and several sub-entities.

You can tell if you need one or the other by answering this questions: is there some other entity in the model which could have an association with the base class?

If yes, then the base class is in fact an entity, and you should use entity inheritance. If no, then the base class is in fact a class that contains attributes and methods that are common to several unrelated entities, and you should use a mapped superclass.

For example:

  • You can have several kinds of messages: SMS messages, email messages, or phone messages. And a person has a list of messages. You can also have a reminder linked to a message, regardless of the kind of message. In this case, Message is clearly an entity, and entity inheritance must be used.
  • All your domain objects could have a creation date, modification date and ID, and you could thus make them inherit from a base AbstractDomainObject class. But no entity will ever have an association to an AbstractDomainObject. It will always be an association to a more specific entity: Customer, Company, whatever. In this case, it makes sense to use a MappedSuperClass.