Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting MappedSuperclass from the database (Hibernate)

Tags:

java

hibernate

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();
like image 979
pek Avatar asked Sep 15 '09 14:09

pek


1 Answers

No if you are using @MappedSuperclass

The reason for this is that when you define base class as @MappedSuperclass, there is no table generated for the base class, instead all of the properties are replicated in the concrete tables. In your example only FullTimeEmployee, PartTimeEmployee and Store tables would exist.

If you want to be able to query for base class entities you need to select different mapping for base classes. Use @Inheritance annotation on the base class and select one of the 3 possible mapping strategies - SINGLE TABLE, TABLE PER CLASS or JOINED

like image 92
Gregory Mostizky Avatar answered Nov 15 '22 23:11

Gregory Mostizky