Problem
I have a @MappedSuperclass
called Data as the parent of every Entity in my database. It contains common attributes like Id etc. I then have an entity that extends Data which is also a @MappedSuperclass
due to common functionality of its subclasses. The mapping in my database is correct.
Here is an example of my hierarchy
@MappedSuperclass Data | @MappedSuperclass +- Employee | | @Entity | +- FullTimeEmployee | | @Entity | +- PartTimeEmployee | @Entity +- Store
And the tables are correctly mapped:
FullTimeEmployee PartTimeEmployee Store
Is there anyway to query the database for all Employee subclasses (FullTimeEmployee, PartTimeEmployee) as instances of Employee without referring the name of the subclasses in the query?
Something like
List<Employee> allEmployees = getAllEmployees();
The idea is that whenever I decide to create another subclass of Employee (i.e. AllDayEmployee) I will not have to change the query to include the name.
Solution
So, as Gregory correctly pointed out, this is not possible with @MappedSuperclass
. So I changed it into @Entity and, since I wanted to preserve a table for each subclass I used InheritanceType.JOINED
.
So the above hierarchy is now
@MappedSuperclass Data | @Entity | @Inheritance(strategy=InheritanceType.JOINED) +- Employee | | @Entity | +- FullTimeEmployee | | @Entity | +- PartTimeEmployee | @Entity +- Store
And the tables are still:
FullTimeEmployee PartTimeEmployee Store
So now, to get all Employees I simply call:
entityManager.createQuery("from Employee").getResultList();