如何在Spring数据休息中返回深层嵌套投影?

时间:2016-08-11 21:45:31

标签: java spring projection spring-data-rest

鉴于这3个实体:

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

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

}

我想为Department创建一个投影,用于返回所有部门及其员工和国籍。我所取得的成就是通过以下方式将所有部门与员工一起退回:

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

@RepositoryRestResource(collectionResourceRel = "department", path = "departments")
public interface DepartmentRepository extends JpaRepository<Department, Long> {
}

1 个答案:

答案 0 :(得分:10)

执行此操作的方法是为嵌套对象创建投影,然后在更全局的投影中使用此投影。因此,根据您的问题,您可以为国籍创建一个投影,然后为部门创建另一个投影以捕获国籍的投影,最后另一个投影以获得部门的实体。

@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();
}

希望它有所帮助!