Query abstract entities

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.