Spring boot 通过RESTAPI创建子对象时传递父id引用
我使用的是SpringBoot(版本-2.1.1)。我通过RESTAPI为CRUD操作公开了一对多数据库模型。模型如下所示。如何配置Spring boot 通过RESTAPI创建子对象时传递父id引用,spring-boot,spring-data-jpa,spring-rest,Spring Boot,Spring Data Jpa,Spring Rest,我使用的是SpringBoot(版本-2.1.1)。我通过RESTAPI为CRUD操作公开了一对多数据库模型。模型如下所示。如何配置POST/departmentsapi(创建department对象)以仅接受输入json主体中的组织id @PostMapping public Long createDepartment(@RequestBody Department Department) { Department d = departmentService.save(
POST/departments
api(创建department对象)以仅接受输入json主体中的组织id
@PostMapping
public Long createDepartment(@RequestBody Department Department) {
Department d = departmentService.save(Department);
return d.getId();
}
注意-我不希望在创建部门时允许创建组织对象
模型对象映射
@Entity
@Table(name="ORGANIZATIONS")
public class Organization{
@Id
@GeneratedValue
Private long id;
@Column(unique=true)
Private String name;
@OneToMany(mappedBy = "organization", fetch = FetchType.EAGER)
private List<Department> departments;
}
@Entity
@Table(name="DEPARTMENTS")
Public class Department{
@Id
@GeneratedValue
Private long id;
@Column(unique=true)
Private String name;
@ManyToOne(fetch = FetchType.EAGER)
private Organization organization;
}
@实体
@表(name=“组织”)
公营班级组织{
@身份证
@生成值
私人长id;
@列(唯一=真)
私有字符串名称;
@OneToMany(mappedBy=“organization”,fetch=FetchType.EAGER)
私人名单部门;
}
@实体
@表(name=“部门”)
公共课系{
@身份证
@生成值
私人长id;
@列(唯一=真)
私有字符串名称;
@manytone(fetch=FetchType.EAGER)
私人组织;
}
谢谢 在我看来,最简单、最明智的方法是利用DTO(数据传输对象)模式 创建一个表示要作为输入获取的模型的类:
public class CreateDepartmentRequest {
private long id;
// getters and setters
}
然后在控制器中使用它:
@PostMapping
public Long createDepartment(@RequestBody CreateDepartmentRequest request) {
Department d = new Department();
d.setId(request.getId());
Department d = departmentService.save(d);
return d.getId();
}
另外,最好始终通过RESTAPI返回JSON(除非在API中使用其他格式)因此,如果您不想创建多个模型,您也可以使用与我上面提到的相同的模式作为POST操作的结果返回适当的模型或简单的映射。我认为最简单、最明智的方法是使用DTO(数据传输对象)模式 创建一个表示要作为输入获取的模型的类:
public class CreateDepartmentRequest {
private long id;
// getters and setters
}
然后在控制器中使用它:
@PostMapping
public Long createDepartment(@RequestBody CreateDepartmentRequest request) {
Department d = new Department();
d.setId(request.getId());
Department d = departmentService.save(d);
return d.getId();
}
另请注意,最好始终通过RESTAPI返回JSON(除非在API中使用其他格式),这样您也可以使用与我上面提到的相同的模式,作为POST操作的结果返回适当的模型,或者如果不想创建多个模型,则返回简单的映射