我有部門和員工之間的多對多關系 
我已經為 GET 端點做了一個映射,它回傳一個包含員工的部門串列,這是請求:http://localhost:8080/api/departments/1/employees,這是我得到的回應:
[
{
"id": {
"deptNo": "1 ",
"empNo": 2
},
"fromDate": "2021-11-22",
"toDate": null
}
]
這是完成作業的代碼:
部門知識庫匯入
@Override
public Optional<Department> findByIdWithEmployees(String deptNo) {
TypedQuery<Department> query = this.entityManager.createQuery("SELECT d FROM Department d JOIN FETCH d.employees e WHERE d.deptNo = :deptNo AND e.toDate IS NULL", Department.class).setParameter("deptNo", deptNo);
return Optional.ofNullable(query.getSingleResult());
}
員工服務實施
@Override
public List<DepartmentEmployee> listAllEmployeesPerDepartment(String deptNo) {
Department department = this.departmentRepository.findByIdWithEmployees(deptNo).orElseThrow(() -> new DepartmentNotFoundException(deptNo));
return department.getEmployees();
}
部門主管
@GetMapping("/{deptNo}/employees")
public List<DepartmentEmployee> getEmployeesPerDepartment(@PathVariable String deptNo) {
return this.employeeService.listAllEmployeesPerDepartment(deptNo);
}
現在我需要的是重新映射它,以便我得到不同的回應。這是我在運行 GET 請求時需要接收的回應:
[
{
"fromDate":"2021-11-22",
"toDate":null,
"employee":{
"empNo":2,
"birthDate":"1997-05-10",
"firstName":"Taulant",
"lastName":"Fazliu",
"gender":"M",
"hireDate":"2020-01-01"
}
}
]
如何實作這一目標?
uj5u.com熱心網友回復:
如果您想要給出的回應與您的模型具有不同的結構(您展示的第一個圖表),您需要實作 DTO 模式。
DTO:d ATA牛逼轉讓(BOT)? bject。用塞繆爾·杰克遜的話來說,這只是意味著“嘿,你!你想以不同的方式展示你的狗屎嗎?創造一個新的混蛋媽媽物件來代表新的狗屎,該死的改造它! ”
因此,創建一個新物件DepartmentEmployeeDTO,使用您要顯示的結構命名,并使用一種Builder模式從一個物件轉換為另一個物件。當然 make getEmployeesPerDepartmentreturn List<DepartmentEmployeeDTO>。該方法最終將是這樣的:
@GetMapping("/{deptNo}/employees")
public List<DepartmentEmployeeDTO> getEmployeesPerDepartment(@PathVariable String deptNo) {
return this.employeeService.listAllEmployeesPerDepartment(deptNo)
.stream()
.map(e -> new DepartmentEmployeeDTOBuilder(e).build())
.collect(Collectors.toList());
}
這為您提供Builder了一個建構式,并將原始建構式DepartmentEmployee作為唯一引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/358238.html
