spring - Spring Boot REST 一对一 - POST 还是 PUT?
问题描述
我正在开发 Spring Boot REST api,现在我遇到了一些logical problem
.
所以我有一个实体“A”,它与实体“B”拥有一对一的关系。最初,实体“A”在没有实体“B”的情况下发布(-> 所以关系为空)。
所以当我想添加实体“B”时,我应该简单地发布它,还是 PUT/PATCH 实体“A”和实体“B”?
解决方案
考虑一个实体的 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的数据来更新它)
推荐阅读
- jenkins - 将 jobdsl 命令扩展到 groovy 类的问题
- javascript - 计数计时器,记录在页面上花费的时间
- html - Github 页面问题 - (错误 404 或根本没有出现)
- processor - 计算执行时间
- python - 执行 jupyter notebook 时出错:ImportError: cannot import name '_RuleList'
- c# - 当返回行时,如何修复 reader.Read() 部分中的输入格式不正确?
- reactjs - 如何将 Redux 连接到 React 功能组件
- c - 我可以将作为命令行参数传递的 .txt 文件保存到 C 中的 char 数组吗?
- python - 是否可以将 dask 数据框与 teradata python 模块一起使用?
- python-3.x - 如何在python 3.7中的图像中对多尺度水平的中心环绕差异执行Earth Mover的距离而不是DoG