Close

JPA - Mapped Superclasses

[Last Updated: Jan 7, 2018]
A quick overview of JPA Mapped Superclasses.
  • A mapped superclass provides persistent entity state and mapping information but is not itself an entity.
  • A mapped superclass, unlike an entity, does not allow querying, persisting, or relationships to the superclass.
  • @MappedSuperclass annotation is used to designate a class as mapped superclass.
  • All mappings annotation can be used on the root class except for @Entity. Also persistent relationships defined by a mapped superclass must be unidirectional.
  • Mapping information may be overridden in the subclasses by using the @AttributeOverride and @AssociationOverride annotations.
  • Both abstract and concrete classes may be specified as mapped superclasses.
  • It is similar to table per class inheritance but no table joins or inheritance exists in data model. There's no table for the mapped superclass. Inheritance only exists in object model.
  • The main disadvantage of using mapped superclass is that we cannot load all entities (subclasses) represented by the mapped superclass, i.e., polymorphic queries are not possible.

Example

@MappedSuperclass
public class Employee {
  @Id
  @GeneratedValue
  private long id;
  private String name;
    .............
}
@Entity
@Table(name = "FULL_TIME_EMP")
public class FullTimeEmployee extends Employee {
  private int salary;
    .............
}
@Entity
@Table(name = "PART_TIME_EMP")
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 FULL_TIME_EMP");
          nativeQuery(em, "SHOW COLUMNS from PART_TIME_EMP");

      } finally {
          emf.close();
      }
  }
    .............
}
'SHOW TABLES'
[FULL_TIME_EMP, PUBLIC]
[PART_TIME_EMP, PUBLIC]
'SHOW COLUMNS from FULL_TIME_EMP'
[ID, BIGINT(19), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
[SALARY, INTEGER(10), NO, , NULL]
'SHOW COLUMNS from PART_TIME_EMP'
[ID, BIGINT(19), NO, PRI, NULL]
[NAME, VARCHAR(255), YES, , NULL]
[HOURLYRATE, INTEGER(10), NO, , NULL]

A quick overview of the mapping:

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("Robert");
      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 FULL_TIME_EMP");
      ExampleMain.nativeQuery(em, "Select * from PART_TIME_EMP");
  }

  private static void loadEntities(EntityManagerFactory emf) {
      System.out.println("-- Loading entities --");
      EntityManager em = emf.createEntityManager();
      List<Employee> entityAList = em.createQuery("Select t from FullTimeEmployee t")
                                     .getResultList();
      entityAList.forEach(System.out::println);

      entityAList = em.createQuery("Select t from PartTimeEmployee t")
                      .getResultList();
      entityAList.forEach(System.out::println);
      em.close();
  }
}
-- Persisting entities --
FullTimeEmployee{id=0, name='Sara', salary=100000}
PartTimeEmployee{id=0, name='Robert', hourlyRate='60'}
-- Native queries --
'Select * from FULL_TIME_EMP'
[1, Sara, 100000]
'Select * from PART_TIME_EMP'
[2, Robert, 60]
-- Loading entities --
FullTimeEmployee{id=1, name='Sara', salary=100000}
PartTimeEmployee{id=2, name='Robert', hourlyRate='60'}

Note that, we cannot create a JPQL query like 'select t from Employee t' which can load all subclasses. That is only possible when we use an inheritance strategy: SINGLE_TABLE or JOINED. or TABLE_PER_CLASS.

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

JPA @MappedSuperClass Example Select All Download
  • mapped-super-class
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Employee.java
          • resources
            • META-INF

    See Also