我正在尝试构建一个具有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
}
部门课程
@Entity
@Table
public class Department {
@Id
@GeneratedValue
private Long Id;
private String name;
//SETTERS AND GETTERS, TWO CONSTRUCTORS
}
员工控制者
@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);
}
}
我需要添加一个部门,然后添加和属于该部门的员工。
这是发给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)
答案 0 :(得分:2)
department
类中的Employee
字段是Department
的实例,而不是整数。因此,您要发布的JSON是错误的。实际上,与通过REST调用发送的类使用相同的类持久化在数据库中是一种不良的体系结构实践。
如果将它们分开(使REST对象成为DTO),则可以收到ID(2),查找ID为2的部门,然后将其放入新的Employee
对象中并将其保存到数据库。
编辑:您可以创建EmployeeDTO类:
public class EmployeeDTO {
private Long id;
private String name;
private Long departmentId;
... // getters
}
您的控制器可能具有如下端点:
@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);
}