Close

Spring Data JPA - Interface Based Nested Projections

[Updated: Aug 29, 2018, Created: Aug 28, 2018]

Following example shows how to use interface based nested Projections.

Example

Entities

@Entity
public class Employee {
  @Id
  @GeneratedValue
  private Integer id;
  private String name;
  @ManyToOne(cascade = CascadeType.ALL)
  private Department department;
  private int salary;
    .............
}
@Entity
public class Department {
  @Id
  @GeneratedValue
  private Integer id;
  private String deptName;
  private String location;
    .............
}

Defining Projections

public interface EmployeeInfo {
  String getName();
  int getSalary();
  DeptInfo getDepartment();

  interface DeptInfo {
      String getDeptName();
  }
}

In above class, EmployeeInfo is the main projection to get the selected attributes and DeptInfo is the nested projection to get department name only.

Creating Repository

public interface EmployeeRepository extends CrudRepository<Employee, Long> {
  List<EmployeeInfo> findBy();
  List<EmployeeInfo> findBySalaryBetween(int salaryMin, int salaryMax);
  List<EmployeeInfo> findByDepartmentLocation(String location);
}

The third query method in above example is nested derived query method which applies condition equivalent to JPQL 'where employee.department.location = ?'.

Example Client

@Component
public class ExampleClient {

  @Autowired
  private EmployeeRepository repo;

  public void run() {
      List<Employee> employees = createEmployees();
      repo.saveAll(employees);

      System.out.println(" -- finding all employees --");
      Iterable<Employee> all = repo.findAll();
      all.forEach(System.out::println);

      System.out.println(" -- All EmployeeInfo --");
      List<EmployeeInfo> list = repo.findBy();
      for (EmployeeInfo ei : list) {
          EmployeeInfo.DeptInfo di = ei.getDepartment();
          System.out.printf("Name: %s, Salary: %s, Dept: %s%n",
                  ei.getName(), ei.getSalary(), di.getDeptName());
      }

      System.out.println(" -- EmployeeInfo with salary between 3000 and 4000 --");
      list = repo.findBySalaryBetween(3000, 4000);
      for (EmployeeInfo ei : list) {
          EmployeeInfo.DeptInfo di = ei.getDepartment();
          System.out.printf("Name: %s, Salary: %s, Dept: %s%n",
                  ei.getName(), ei.getSalary(), di.getDeptName());
      }

      System.out.println(" -- EmployeeInfo with dept Location TX --");
      list = repo.findByDepartmentLocation("TX");
      for (EmployeeInfo ei : list) {
          EmployeeInfo.DeptInfo di = ei.getDepartment();
          System.out.printf("Name: %s, Salary: %s, Dept: %s%n",
                  ei.getName(), ei.getSalary(), di.getDeptName());
      }
  }

  private List<Employee> createEmployees() {
      return Arrays.asList(
              Employee.of("Diana", Department.of("Admin", "NY"), 3000),
              Employee.of("Mike", Department.of("IT", "TX"), 35000),
              Employee.of("Rose", Department.of("Sales", "NC"), 4000),
              Employee.of("Sara", Department.of("Admin", "TX"), 3500),
              Employee.of("Joe", Department.of("IT", "TX"), 3000),
              Employee.of("Charlie", Department.of("IT", "NY"), 4500)
      );
  }
}
public class ExampleMain {

  public static void main(String[] args) {
      AnnotationConfigApplicationContext context =
              new AnnotationConfigApplicationContext(AppConfig.class);
      ExampleClient exampleClient = context.getBean(ExampleClient.class);
      exampleClient.run();
      EntityManagerFactory emf = context.getBean(EntityManagerFactory.class);
      emf.close();
  }
}
 -- finding all employees --
Employee{id=1, name='Diana', department=Department{id=2, deptName='Admin', location='NY'}}
Employee{id=3, name='Mike', department=Department{id=4, deptName='IT', location='TX'}}
Employee{id=5, name='Rose', department=Department{id=6, deptName='Sales', location='NC'}}
Employee{id=7, name='Sara', department=Department{id=8, deptName='Admin', location='TX'}}
Employee{id=9, name='Joe', department=Department{id=10, deptName='IT', location='TX'}}
Employee{id=11, name='Charlie', department=Department{id=12, deptName='IT', location='NY'}}
-- All EmployeeInfo --
Name: Diana, Salary: 3000, Dept: Admin
Name: Mike, Salary: 35000, Dept: IT
Name: Rose, Salary: 4000, Dept: Sales
Name: Sara, Salary: 3500, Dept: Admin
Name: Joe, Salary: 3000, Dept: IT
Name: Charlie, Salary: 4500, Dept: IT
-- EmployeeInfo with salary between 3000 and 4000 --
Name: Diana, Salary: 3000, Dept: Admin
Name: Rose, Salary: 4000, Dept: Sales
Name: Sara, Salary: 3500, Dept: Admin
Name: Joe, Salary: 3000, Dept: IT
-- EmployeeInfo with dept Location TX --
Name: Mike, Salary: 35000, Dept: IT
Name: Sara, Salary: 3500, Dept: Admin
Name: Joe, Salary: 3000, Dept: IT

Example Project

Dependencies and Technologies Used:

  • spring-data-jpa 2.0.9.RELEASE: Spring Data module for JPA repositories.
    Uses org.springframework:spring-context version 5.0.8.RELEASE
  • hibernate-core 5.3.5.Final: Hibernate's core ORM functionality.
    Implements javax.persistence:javax.persistence-api version 2.2
  • h2 1.4.197: H2 Database Engine.
  • JDK 1.8
  • Maven 3.5.4

Nested Projection Example Select All Download
  • spring-data-jpa-interface-based-nested-projections
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EmployeeInfo.java
          • resources
            • META-INF

    See Also