Loading...

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):

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

The subclasses:

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

The repository query:

public class EmployeeRepositoryImpl implements EmployeeRepository {
    //..
    @Override
    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();
@Before
public void setUp() throws Exception {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("h2mem");
    em = factory.createEntityManager();
    repository = new EmployeeRepositoryImpl();
    repository.setEntityManager(em);
    em.getTransaction().begin();
    em.persist(joe);
    em.persist(jane);
    em.getTransaction().commit();
}
@Test
public void testFindAll() {
    //act
    List<? extends Employee> employeeList = this.repository.findAll();
    //assert
    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.

jpa
Please remember the terms for blog comments.