如何解决在 Spring Boot 和 PostgreSQL 中使用 OneToMany 关系
帖子实体:
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
private String content;
@OnetoMany(mappedBy = "post",cascade = CascadeType.ALL,orphanRemoval = true)
private List<Comment> comments = new ArrayList<>();
评论实体:
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue
private Long id;
private String content;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
为了可读性,省略了 getter 和 setter。
当我通过 PostController 发送 POST 请求时,我可以在我的 Postgresql 数据库中存储一个新的 Post。如何通过控制器向此帖子添加新评论?我似乎在任何地方都找不到答案。
解决方法
因此,您在这里创建了一个双向关系,因此需要更新帖子实体和评论实体。
假设您的评论路径是 /post/{postId}/comment
,并且您使用的是 Sping JPA(comment
和 post
的存储库为 commentRepository
和 {{1} } 分别。)
然后控制器方法看起来像 -
postRepository
另一种选择是创建单向关系,所以
@PostMapping("/post/{postId}/comment")
public ResponseEntity postController(@PathParam("postId") Long postId,@RequestBody Comment comment) {
Post post = postRepository.getById(postId);
comment.setPost(post);
post.getComments().add(comment);
commentRepository.save(comment);
postRepository.save(post);
}
@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
private String content;
然后,您只需要在 POST 请求上更新评论实体,如果您需要获取帖子的所有评论,您可以这样做 -
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue
private Long id;
private String content;
@ManyToOne
@JoinColumn(name = "post_id")
private Post post;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。