Let's assume I have an entity called Employee, which contains 10 columns. I have some other entites like Manager, Salesman, Lawyer and HumanResource. All these classes will inherit from Employee and gonna have one or two different fields of their own. What I want to do is avoid all the duplicate values saved in the database. If I use @MappedSuperclass, all fields will be saved into all tables and therefore duplicates. If I use @Embedded, the result will be the same. I wonder what other options do I have, beside creating Employee entity/table with @OneToMany relationship with the other entites?
1 Answer
You can use @Inheritance(strategy=InheritanceType.JOINED) to have all 10 fields from Employee base class in single Employee table.
@Inheritance(strategy=InheritanceType.JOINED)
@Entity
public abstract class Employee {...}
@Entity
public class Manager{
}
In case of using InheritanceType.JOINED additional table will be created for each @Entity subclass.
Read about different Inheritance Strategies (Single Table, Joined table, Table per class) here: https://www.tutorialspoint.com/jpa/jpa_advanced_mappings.htm
@MappedSuperclassis only for handling cases where there is inheritance in the Java domain model and not in the database. For inheritance in the model and in the database see stackoverflow.com/questions/9667703/…@Interitance. Is a@NamedQuerydefined in the superclass accessible from child classes?