【发布时间】:2019-10-01 15:59:34
【问题描述】:
我在 Spring Boot 中编写了一个测试应用程序。员工与部门有关系。 CRUD 有效,但我不确定我的做法是否正确。
当我要创建一个新员工时,我必须发送以下帖子请求
"id": 3,
"firstname": "John",
"lastname": "Doe",
"salary": 50000,
"department": {
"id": 2,
"name": "Sales"
}
}
这是员工类:
@Entity
public class Employee {
@Id
@GeneratedValue
private Long id;
private String firstname;
private String lastname;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "department_id", referencedColumnName="id")
private Department department;
private int salary;
这是 EmployeeController 中的 create 方法:
@PostMapping("/employees")
public Employee create(@RequestBody Employee employee) {
return employeeService.add(employee);
}
部门条目已存在。 是否可以在不填写完整关系的情况下创建员工 (部)? 我只想添加部门ID。但是如果我这样做,json数据中的name字段为空(获取请求)
id 3
firstname "John"
lastname "Doe"
department
id 2
name null
salary 50000
有没有更好的方法?
【问题讨论】:
标签: json spring rest spring-boot jpa