Query abstract entities

:heavy_exclamation_mark: This post is older than a year. Consider some information might not be accurate anymore. :heavy_exclamation_mark:

This post demonstrates a part of inheritance with JPA 2. Abstract entities (classes) can be used to query their concrete subclasses.

An abstract class can be specified as an entity. An abstract entity differs from a concrete entity only in that it cannot be directly instantiated. An abstract entity is mapped as an entity and can be the target of queries (which will operate over and/or retrieve instances of its concrete subclasses).

2.11.1 Abstract Entity Classes, JSR-317, Java Persistence 2.0, Page 52 The class structure: query-abstract-entity

The parent class (abstract entity):

@Inheritance(strategy = JOINED)
@Table(schema = "HR", name = "EMP")
public abstract class Employee {
  // ..

The subclasses:

public class FullTimeEmployee extends Employee {
    private BigDecimal salary;
public class PartTimeEmployee extends Employee {
    private BigDecimal hourlyWage;

The repository query:

public class EmployeeRepositoryImpl implements EmployeeRepository {
    public List<? extends Employee> findAll() {
        TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e", Employee.class);
        return query.getResultList();

The test:

private PartTimeEmployee joe = createPartTimeEmployee();
private FullTimeEmployee jane = createFullTimeEmployee();
public void setUp() throws Exception {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("h2mem");
    em = factory.createEntityManager();
    repository = new EmployeeRepositoryImpl();
public void testFindAll() {
    List<? extends Employee> employeeList = this.repository.findAll();
    assertEquals("found 2 employees", 2, employeeList.size());
    assertThat("Check both employess", employeeList, contains(jane, joe));

Check out the code from the commit revision at github.

Please remember the terms for blog comments.