spring-boot - 如何使用 Spring-Data-Rest 通过不可为空的连接列在单向关系中创建和链接子实体
问题描述
当它们之间的关系是一对多+单向(特别是从父级到子级)时,我无法弄清楚如何使用 Spring-Data-Rest 添加子实体(让我们说一个comment
实体到父实体)post
以及当数据库在子实体表上使用不可为空的连接列时。
对于使用 Spring-Data-Rest 链接关系中的两个实体,我相信通常的方法是首先创建两个实体(对它们各自的端点进行 POST 调用),然后用 PUT 或 PATCH 将它们链接到关系端点,例如作为/api/posts/1/comments
. 该链接请求的正文将包含指向先前创建的子实体的链接,例如http://localhost:8080/api/comments/1
. 但是,对于我在子实体上具有不可为空的连接列的情况,当我尝试创建子实体时,我无法创建子实体,因为它无法使用连接列的null
值插入到数据库中。parent_id
@Entity
public class Post {
@Id
private Long id;
private String title;
@OneToMany
@JoinColumn(name = "post_id", nullable = false)
private List<Comment> comments;
}
@Entity
public class Comment {
@Id
private Long id;
private String message;
}
@RepositoryRestResource
interface PostRestRepository implements JpaRepository<Post, Long> {}
@RepositoryRestResource
interface CommentRestRepository implements JpaRepository<Comment, Long> {}
尝试通过 POST 调用创建子实体时/api/comments
,我在响应正文中收到此错误:ERROR: null value in column \"post_id\" violates not-null constraint
。
我假设在这种情况下有一种方法可以创建评论并将评论链接到帖子,但我无法在任何地方找到答案。
解决方案
推荐阅读
- javascript - 如何在python中解析使用javascript使用json stringfy创建的json
- python - 如何在 for 循环中将字典附加到字典中?
- github - “Github Pull Request 允许维护者修改”的用例是什么?
- phaser-framework - Phaser 3 ScaleManager 异常
- oracle - Oracle 约束 - 比较两个字符串两次
- angular - 如何以角度呈现api数据?
- machine-learning - 使用 RobustScaler 时,您应该转换 y train 吗?
- exception - ESP8266 在向服务器发出第二次请求后重启(异常 9)
- firebase - Flutter 中的 Firebase Admob:即使广告正在加载,也要处理广告
- git - 如何使用 git 从 GitHub 中的远程仓库中删除提交?