gpt4 book ai didi

java - 多对一关系的 API 请求

转载 作者:行者123 更新时间:2023-12-02 01:31:13 25 4
gpt4 key购买 nike

我正在尝试构建一个具有 ManyToOne 关系的 API。它与员工和部门实体有关。这就是我所拥有的:

@Entity
@Table
public class Employee {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long Id;
private String name;
@ManyToOne(fetch=FetchType.LAZY)
private Department department;
//SETTERS AND GETTERS, TWO CONSTRUCTORS
}

院系类(class)

 @Entity
@Table
public class Department {

@Id
@GeneratedValue
private Long Id;
private String name;
//SETTERS AND GETTERS, TWO CONSTRUCTORS
}

员工 Controller

@RestController
public class EmployeeController {

@Autowired
EmployeeService employeeService;

@PostMapping("/employee")
public Employee create (@RequestBody Employee employee){

return employeeService.create(employee);
}
}

部门主管

 @RestController
public class DepartmentController {

@Autowired
private DepartmentService departmentService;

@PostMapping("/departments")
public Department create(@RequestBody Department department) {
return departmentService.create(department);
}
}

我需要添加一个部门,然后添加属于该部门的员工。

这是向部门发送的 POST 请求,它有效。

{
"id": 2,
"name": "Depto"
}

我需要将该部门添加到员工

 {
"id": 2,
"name": "Employee",
"department": 2
}

这是我得到的错误:

 .HttpMessageNotReadableException: Could not read document: Cannot construct instance of 'mypackage.Department' (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (2)

最佳答案

Employee 类中的 department 字段是 Department 的实例,而不是整数。所以你发布的 JSON 是错误的。事实上,使用与通过 REST 调用发送的内容相同的类来持久保存在数据库中是不好的架构实践。

如果将它们分开(使 REST 对象成为 DTO),那么您可以接收 id (2),查找 id 2 的部门,然后将其放入新的 Employee 对象中,然后将其保存到数据库。

编辑:您可以创建一个 EmployeeDTO 类:

public class EmployeeDTO {
private Long id;
private String name;
private Long departmentId;

... // getters
}

你的 Controller 可能有一个像这样的端点:

@PostMapping("/employee")
public Employee create (@RequestBody EmployeeDTO employeeDTO){

Department department = departmentService.get(employeeDTO.getDepartmentId());

Employee employee = new Employee();
employee.setId(employeeDTO.getId());
employee.setName(employeeDTO.getName());
employee.setDepartment(department);

return employeeService.create(employee);
}

关于java - 多对一关系的 API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56031354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com