Reputation: 328
In JPA/Hibernate, can a mapped super class like BetterBaseEntity
be a subclass of another mapped super class BaseEntity
?
I want to retain BaseEntity
because nearly everyone uses it but would like to add some new parent functionality.
Upvotes: 4
Views: 2828
Reputation: 34
Relational databases don’t have a straightforward way to map class hierarchies onto database tables.
To address this, the JPA specification provides several strategies:
MappedSuperclass – the parent classes, can’t be entities
Single Table – the entities from different classes with a common ancestor are placed in a single table
Joined Table – each class has its table and querying a subclass entity requires joining the tables
Table-Per-Class – all the properties of a class, are in its table, so no join is required
Each strategy results in a different database structure.
Entity inheritance means that we can use polymorphic queries for retrieving all the sub-class entities when querying for a super-class.
Since Hibernate is a JPA implementation, it contains all of the above as well as a few Hibernate-specific features related to inheritance.
MappedSuperclass:-
Using the MappedSuperclass strategy, inheritance is only evident in the class, but not the entity model.
Let’s start by creating a Person class which will represent a parent class:
@MappedSuperclass
public class Person {
@Id
private long personId;
private String name;
// constructor, getters, setters
} Notice that this class no longer has an @Entity annotation, as it won’t be persisted in the database by itself.
Next, let’s add an Employee sub-class:
@Entity
public class MyEmployee extends Person {
private String company;
// constructor, getters, setters
}
In the database, this will correspond to one “MyEmployee” table with three columns for the declared and inherited fields of the sub-class.
If we’re using this strategy, ancestors cannot contain associations with other entities.
For more details refer -
https://ritesh-shukla.blogspot.com/2018/10/hibernate-inheritance-mapping.html?m=1
Upvotes: 1