I have one JPA superclass and dozens of subclasses. Most of those subclasses do not add specific properties.
When using InheritanceType.JOINED JPA assumes a sub-table for each subclass, resulting in a large number of obsolete database tables, making database administration and queries harder.
My superclass currently looks like this:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "type")
public abstract class Employee {
@Id public int id;
public String firstName;
public String lastName;
public Date birthday;
}
Some subclasses have specific fields:
@Entity
public class ProjectManager extends Employee {
public String project;
}
Most subclasses, however, are empty like that:
@Entity
public class Director extends Employee {
}
@Entity
public class FacilityManager extends Employee {
}
These database tables make sense:
employee(id, first_name, last_name, birthday)
project_manager(id, project)
How can I avoid these obsolete tables?
director(id)
facility_manager(id)
If I just do not create them, JPA-validation fails:
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
...
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing table [director]
at org.hibernate.tool.schema.internal.SchemaValidatorImpl.validateTable(SchemaValidatorImpl.java:67) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
...
There is a solution but only when using EclipseLink. Hibernate does not support this:
Mixed Inheritance
JPA requires the inheritance strategy to only be defined in the root class. If you want to use a mixture of SINGLE_TABLE and JOINED this can be achieved through using JOINED inheritance in the root class, and specifying the Table on the subclass to be the same as the parent.
Example: Using JOINED with mixed inheritance
@Entity
// This subclass does not define its own table, but shares its parent's ACCOUNT table.
@Table(name="ACCOUNT")
@DiscriminatorValue("3")
public class StandardAccount extends Account {
...
}
Source: https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/Inheritance#Mixed_Inheritance
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