Close

JPA - Single Table Inheritance Strategy

[Last Updated: Jan 7, 2018]
A quick overview of JPA single table inheritance strategy.
  • In this strategy, all the classes in a hierarchy are mapped to a single table.
  • The annotation @Inheritance is used on the root entity class with strategy = InheritanceType.SINGLE_TABLE.
  • @DiscriminatorColumn is used on the root entity class to specify the discriminator column attributes. Discriminator is a way to differentiate rows belonging to different classes in the hierarchy.
  • @DiscriminatorValue is used on each persistable concrete class to specify a unique discriminator value.
  • @Entity and other meta-data annotations are used on the root and subclasses as usual.
  • @Id field should only be defined in the root class.
  • The root class can be abstract or a concrete class. An abstract entity differs from a concrete entity only in that it cannot be directly instantiated.
  • This is the default inheritance strategy. That means if we don't specify the strategy attribute of @Inheritance annotation on the the root class or don't use this annotation at all , then InheritanceType.SINGLE_TABLE strategy is assumed.
  • This strategy has the disadvantage of having rows with null column values for which the entity has no corresponding fields.

Example

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Entity
@DiscriminatorColumn(name = "EMP_TYPE")
public class Employee {
  @Id
  @GeneratedValue
  private long id;
  private String name;
    .............
}
@Entity
@DiscriminatorValue("F")
public class FullTimeEmployee extends Employee {
  private int salary;
    .............
}
@Entity
@DiscriminatorValue("P")
public class PartTimeEmployee extends Employee {
  private int hourlyRate;
    .............
}
public class ExampleMain {

  public static void main(String[] args) {
      EntityManagerFactory emf =
              Persistence.createEntityManagerFactory("example-unit");
      try {
          EntityManager em = emf.createEntityManager();
          nativeQuery(em, "SHOW TABLES");
          nativeQuery(em, "SHOW COLUMNS from EMPLOYEE");

      } finally {
          emf.close();
      }
  }

  public static void nativeQuery(EntityManager em, String s) {
      System.out.printf("'%s'%n", s);
      Query query = em.createNativeQuery(s);
      List list = query.getResultList();
      for (Object o : list) {
          if (o instanceof Object[]) {
              System.out.println(Arrays.toString((Object[]) o));
          } else {
              System.out.println(o);
          }
      }
  }
}
'SHOW TABLES'
[EMPLOYEE, PUBLIC]
'SHOW COLUMNS from EMPLOYEE'
[EMP_TYPE, VARCHAR(31), NO, , NULL]
[ID, BIGINT(19), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
[HOURLYRATE, INTEGER(10), YES, , NULL]
[SALARY, INTEGER(10), YES, , NULL]

A quick overview:

Persisting and loading data

public class ExampleMain2 {

  public static void main(String[] args) throws Exception {
      EntityManagerFactory emf =
              Persistence.createEntityManagerFactory("example-unit");
      try {
          persistEntities(emf);
          runNativeQueries(emf);
          loadEntities(emf);
      } finally {
          emf.close();
      }
  }

  private static void persistEntities(EntityManagerFactory emf) throws Exception {
      System.out.println("-- Persisting entities --");
      EntityManager em = emf.createEntityManager();

      FullTimeEmployee e1 = new FullTimeEmployee();
      e1.setName("Sara");
      e1.setSalary(100000);
      System.out.println(e1);

      PartTimeEmployee e2 = new PartTimeEmployee();
      e2.setName("Tom");
      e2.setHourlyRate(60);
      System.out.println(e2);

      em.getTransaction().begin();
      em.persist(e1);
      em.persist(e2);
      em.getTransaction().commit();
      em.close();
  }

  private static void runNativeQueries(EntityManagerFactory emf) {
      System.out.println("-- Native queries --");
      EntityManager em = emf.createEntityManager();
      ExampleMain.nativeQuery(em, "Select * from Employee");
  }

  private static void loadEntities(EntityManagerFactory emf) {
      System.out.println("-- Loading entities --");
      EntityManager em = emf.createEntityManager();
      List<Employee> entityAList = em.createQuery("Select t from Employee t")
                                     .getResultList();
      entityAList.forEach(System.out::println);
      em.close();
  }
}
-- Persisting entities --
FullTimeEmployee{id=0, name='Sara', salary=100000}
PartTimeEmployee{id=0, name='Tom', hourlyRate='60'}
-- Native queries --
'Select * from Employee'
[F, 1, Sara, null, 100000]
[P, 2, Tom, 60, null]
-- Loading entities --
FullTimeEmployee{id=1, name='Sara', salary=100000}
PartTimeEmployee{id=2, name='Tom', hourlyRate='60'}

Example Project

Dependencies and Technologies Used:

  • h2 1.4.196: H2 Database Engine.
  • hibernate-core 5.2.10.Final: The core O/RM functionality as provided by Hibernate.
    Implements javax.persistence:javax.persistence-api version 2.1
  • JDK 1.8
  • Maven 3.3.9

Single Table Strategy Example Select All Download
  • jpa-single-table-inheritance
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java
          • resources
            • META-INF

    See Also