【问题标题】:Passing parent id reference when creating child object through REST api通过 REST api 创建子对象时传递父 ID 引用
【发布时间】:2019-01-24 13:09:19
【问题描述】:

我正在使用 Spring Boot(版本 - 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;
}

谢谢!

【问题讨论】:

    标签: spring-boot spring-data-jpa spring-rest


    【解决方案1】:

    在我看来,最简单、最明智的方法是利用 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();
    }
    

    旁注,最好总是通过 REST API 返回 JSON(除非您在 API 中使用其他格式),因此您也可以使用我上面提到的相同模式来返回正确的模型作为 POST 操作的结果如果您不想创建多个模型,则可以使用简单的 Map。

    【讨论】:

      猜你喜欢
      • 2012-01-05
      • 2019-06-05
      • 2019-03-02
      • 1970-01-01
      • 2017-09-11
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多