MappedSuperclass uses inheritance to reuse fields and code. For example, if you want all your entities to have Long id and Long version fields, you can do them all to extend the BaseEntity class annotated with MappedSuperclass containing these two fields along with their receivers, setters, etc. . But you would never have an entity connected to BaseEntity: the association will always be with a specific subclass of BaseEntity.
The parent object is used for "entity polymorphism." For example, you can imagine two types of Message : EmailMessage and SmsMessage . Both will contain the source, purpose, and body. But EmailMessage will have an email address and subject, while SmsMessage will have a phone number.
And you could imagine a Person object containing a collection of sent messages of type Message . The collection actually contains instances of EmailMessage and SmsMessage. Hibernate will decide which one should be created depending on the inheritance strategy used for inheritance:
- all messages can be stored in the same table, and Hibernate will use the discriminator column containing the message type
- EmailMessage can be stored in one table, and SmsMessage can be stored in another
- or fields common to both objects (source, target, body) can be stored in the comon table, fields specific to EmailMessage in the second table, and fields related to SmsMessage in the third table.
source share