Lets say I have a REST resource like:
/companies/{companyId}/departments/{departmentId}/employees/{employeeId}
and entity classes where CompanyEntity has List<DepartementEntity>
and DepartmentEntity has List<EmployeeEntity>
.
All IDs are unique.
So now somebody is calling
GET /companies/{companyId}/departments/{departmentId}/employees/{employeeId}
What is a good way to find the employee with {employeeId} in Spring Data JPA / Hibernate?
Way:
employeeRepository.findOne(employeeId);
Pro: Just 1 query
Contra: companyId and departmentId are unused. They can even be random. And this is rather GET /employee/{id} but I want to keep the nested resources with company and department.
Also I would like to access company object to check if the one who is asking is in the same company as the employee.
Way:
company = companyRepository.findOne(companyId);
for(DepartmentEntity department : company.getDepartments()) {
if(department.getId() == departmentId) { for(EmployeeEntity employee : department.getEmployees()) { if(employee.getId() == employeeId) return employee; } }
}
Pro: companyId and departementId are considered
Contra: Many queries if you use lazy loading
Thanks.
if (employee.getDepartment().getId() != departmentId || employee.getDepartment().getCompany().getId() != companyId) { throw ... }
– JB Nizet