首页 > 解决方案 > Spring Boot REST 一对一 - POST 还是 PUT?

问题描述

我正在开发 Spring Boot REST api,现在我遇到了一些logical problem.

所以我有一个实体“A”,它与实体“B”拥有一对一的关系。最初,实体“A”在没有实体“B”的情况下发布(-> 所以关系为空)。

所以当我想添加实体“B”时,我应该简单地发布它,还是 PUT/PATCH 实体“A”和实体“B”?

标签: springspring-boothibernaterestspring-rest

解决方案


考虑一个实体的 A 和 B 并取 firstName 和 lastName 字段:

@Entity
public class A {

    @Id
    private Integer id;

    private String firstName;

    @OneToOne(mappedBy = "a")
    private B b; 
}

@Entity
public class B {

    @Id
    private Integer id;
 
    private String lastName;

    @OneToOne
    private A a;
}

存储库是:

@Repository 
 public interface ARepo extends JpaRepository<A,Integer> {
}
@Repository
 public interface BRepo extends JpaRepository<B,Integer> {
}

让我们使用@postContruct 在A 实体中保存一些数据

@PostConstruct
void init(){
    A a = new A(1,"ABCD");
    aRepo.save(a);
}

用于保存 B 实体的控制器:

 @PostMapping("/saveB")
 public String save(@RequestBody B b){
    bRepo.save(b);
    return "ok";
 }

和 json 用于保存 B 实体:

{ "id":1, "lastName":"xyz", "a":{ "id":1 } }

根据我的理解,如果我们从 B 存储库中保存实体,我们需要使用 @PostMapping(插入新行),或者我们可以使用 A 存储库来保存 B 实体,因为这里的映射是双向的,通过使用 @PutMapping (数据库中已经存在A数据,我们需要通过添加B的数据来更新它)


推荐阅读