通过 REST 创建子对象时传递父 ID 引用 api

Passing parent id reference when creating child object through REST api

我正在使用 spring 启动(版本 - 2.1.1)。我有一个通过 rest api 为 CRUD 操作公开的一对多数据库模型。该模型如下所示。如何配置 POST /departments api(创建部门对象)以仅接受输入 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;
}

谢谢!

我认为最简单、最明智的方法是使用 DTO(数据传输对象)模式。

创建一个 class 来表示您想要作为输入获得的模型:

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();
}

旁注,最好始终 return JSON 通过 REST API(除非您在 API 中使用其他格式),因此您也可以利用与我上面提到的相同模式 return 作为 POST 操作或简单 Map 的结果的适当模型,如果你不想创建许多模型。