REST API:如果从 JSON 中删除,关系会中断吗?

REST API : breaking relationship if removed from JSON?

我正在使用 Spring Data JPA / hibernate / Spring Boot 构建一个 API。 假设我有这个 JSON 这个请求:GET /Parents/1

{
"id": 1,
"name": "Dad",
"adoptedChildren": [
    {
        "id": 1,
        "name": "Marie",
        "age": 10
    },
    {
        "id": 1,
        "name": "Robert",
        "age": 9
    }
]
}

简直就是一个Parent有两个领养的child人。 现在无论出于何种原因,这个 parent 丢失了一个 child,所以我收到了这个 PUT 请求:PUT /Parents/1

{
"id": 1,
"name": "Dad",
"adoptedChildren": [
    {
        "id": 1,
        "name": "Robert",
        "age": 9
    }
]
}

JSON 少了一个 child。

我有两个问题:

  1. 这是允许打破 Parent 和 Child 之间的 link 的正确方法吗? child不删,我只需要打破两者之间的关系?

  2. 我是否应该仅在 Child 资源上允许 PUT 操作,以强制用户从 Child 端更新关系?

  3. 如果解决方案 (1) 没问题,您如何使用 Spring Data JPA 进行此更新?当我用缺失的 child 更新实体时,它只是忽略它!

    @PutMapping("parents/{id}")
    public ItineraryDTO updateItinerary(@PathVariable int id, 
    @RequestBody Parent parent){
       return parentRepository.save(parent);
    }
    

IMO 这完全取决于您的型号。

1) 如果您的 'children' 是依赖实体并且没有自己的存储库,那么您的选择是 #1。但是在这种情况下,您应该更正 Parent class 以使它们在保存父实体及其嵌套子实体时正常工作:

@Entity
public class Parent {
    //...
    @OneToMany(cascade = ALL, orphanRemoval = true)
    private List<Child> children;
    //...
} 

2) 如果你的 'children' 是独立的对象并且它们有自己的 repo,那么你应该选择第二个选项 - 只需删除对前一个父对象的引用(将其设置为 null)从子实体更新它:

@Entity
public class Parent {
    //...
    @OneToMany(mappedBy = "parent")
    private List<Child> children;
    //...
} 

@Entity
public class Child {
    //...
    @ManyToOne
    private Parent parent;
    //...
    public Child removeParent() {
         parent = null;
         return this;
    }
} 

@PutMapping("/childrent/{childId}/remove_parent")
public ResponseEntity removeParent(@PathVariable("childId") Long childId) {
    return childRepo.findById(childId)
        .map(c -> ResponseEntity.ok(childRepo.save(c.removeParent())))
        .orElse(ResponseEntity.notFound().build())
}

P.S。这只是示意图模型-在实际项目中,您应该将实体保存在服务层中。