I would like to know what is the difference between MappedSuperclass
and Entity Abstract Class
when one wants to derive from a super class in Hibernate
. I know that Hibernate
does not create a Table in the Database for a MappedSuperclass
. I read in the JavaEE
doc "Abstract entities are like concrete entities but cannot be instantiated". Since they cannot be instantiated, I deduce that there is no matching Table in the Database. Am I right?
If so, what are virtually the difference between using a MappedSuperclass
and an Entity Abstract Class
and what is the impact on the Software and in the Database in each case?
Mapped superclasses cannot be queried and can't be used in EntityManager or Query operations. You must use entity subclasses of the mapped superclass in EntityManager or Query operations. Mapped superclasses can't be targets of entity relationships. Mapped superclasses can be abstract or concrete.
If you have a single hierarchy, prefer To use Single Table Inheritance strategy. Joined strategy is better designed when you have a complex hierarchy but it suffers due To performance issues when querying for any entity. Save this answer.
An abstract class may be declared an entity by decorating the class with @Entity. Abstract entities are like concrete entities but cannot be instantiated.
A mapped superclass is a special type of class that is not persistent itself, but has subclasses that are persistent. A mapped superclass is useful for defined a common persistence superclass that defines common behavior across a set of classes, such as an id or version attribute.
A MappedSuperclass uses inheritance for field and code reuse. For example, if you want all your entities to have a Long id
and a Long version
field, you could make them all extend a BaseEntity
class annotated with MappedSuperclass
containing these two fields, along with their getters, setters, etc. But you would never have an entity having an association with a BaseEntity: the association would always be with a specific subclass of BaseEntity.
A parent entity is used for "entity polymorphism". For example, you could imagine having two kinds of Message
: an EmailMessage
and a SmsMessage
. Both would contain a source, a target, and a body. But EmailMessage would have an email address and a subject, whereas SmsMessage would have a phone number.
And you could imagine having a Person
entity containing a collection of sent messages, of type Message
. The collection would in fact contain instances of EmailMessage and of SmsMessage. Hibernate would decide which one to instantiate depending on the inheritance strategy used for the inheritance mapping:
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