Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return deep nested projections in Spring data rest?

Given this 3 entities:

@Entity
class Department{
    Set<Employee> employees;
    Set<Employee> getEmployees(){
        return this.employees;
    };    
}

@Entity
class Employee{
    Nationality nationality;
    Nationality getNationality(){
        this.nationality;
    }
}
@Entity
class Nationality{

}

I want to create a projection for Department that returns all departments with their employees and nationalities. What I have achieved is to return all departments with their employees using:

@Projection(name = "fullDepartment", types = { Department.class })
public interface DepartmentsProjection {
    Set<Employee> getEmployees();
}

@RepositoryRestResource(collectionResourceRel = "department", path = "departments")
public interface DepartmentRepository extends JpaRepository<Department, Long> {
}
like image 802
Songo Avatar asked Aug 11 '16 21:08

Songo


Video Answer


1 Answers

A way to do this is to create a Projection for your nested(s) object, and then use this projection in a more global one. So following your problem, you can create a projection for Nationality, then another one for Department that has a getter to catch Nationality's projection, and finally another projection to get Department's entity.

@Projection(name = "NationalityProjection", types = { Nationality.class })
public interface NationalityProjection{
    // getters of all attributes you want to project
}

@Projection(name = "EmployeeProjection", types = { Employee.class })
public interface EmployeeProjection{
    NationalityProjection getNationality();
}

@Projection(name = "DepartmentProjection", types = { Department.class })
public interface DepartmentProjection{
    Set<EmployeeProjection> getEmployees();
}

Hope it helps!

like image 80
alonso_50 Avatar answered Oct 12 '22 04:10

alonso_50