0

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?

gozluklu_marti
  • 79
  • 1
  • 7
  • 26
  • 1
    `@MappedSuperclass` is 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 https://stackoverflow.com/questions/9667703/jpa-implementing-model-hierarchy-mappedsuperclass-vs-inheritance – Alan Hay Nov 06 '19 at 17:58
  • @AlanHay I have a quick question regarding `@Interitance`. Is a `@NamedQuery` defined in the superclass accessible from child classes? – oxyt Nov 07 '19 at 15:44

1 Answers1

1

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

Petr Aleksandrov
  • 1,434
  • 9
  • 24