在 Spring Boot 和 PostgreSQL 中使用 OneToMany 关系

Using OneToMany relation in Spring Boot and PostgreSQL

我有两个实体,Post 和评论。

Post实体:

@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。

当我通过 Post 控制器发送 POST 请求时,我可以在我的 PostgreSQL 数据库中存储一个新的 Post。如何通过控制器向 Post 添加新评论?我好像到处都找不到答案。

因此,您在这里创建了双向关系,因此需要更新 post 实体和评论实体。

假设您的评论路径是 /post/{postId}/comment,并且您正在使用 Sping JPA(commentpost 的存储库为 commentRepository 和 [=分别为 18=]。)

那么控制器方法将类似于 -

@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;
@Entity
@Table(name = "comments")
public class Comment {

    @Id
    @GeneratedValue
    private Long id;

    private String content;

    @ManyToOne
    @JoinColumn(name = "post_id")
    private Post post;

然后,您只需要在 POST-request 上更新评论实体,如果您需要获取 post 的所有评论,您可以执行 -

List<Comment> comments = commentRepository.getByPostId(postId);