【问题标题】:Using OneToMany relation in Spring Boot and PostgreSQL在 Spring Boot 和 PostgreSQL 中使用 OneToMany 关系
【发布时间】:2021-06-05 11:14:50
【问题描述】:

我有两个实体,帖子和评论。

发布实体:

@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。如何通过控制器向这篇文章添加新评论?我似乎在任何地方都找不到答案。

【问题讨论】:

    标签: java postgresql spring-boot http-post hibernate-onetomany


    【解决方案1】:

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

    假设您的 cmets 路径是 /post/{postId}/comment,并且您使用的是 Sping JPA(commentpost 的存储库分别为 commentRepositorypostRepository。)

    然后控制器方法看起来像 -

    @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 上更新评论实体,如果您需要获取帖子的所有 cmets,您可以这样做 -

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

    【讨论】:

    • 这条线是做什么的:postRepository.save(post);,因为没有这条线它也可以工作。
    • 用于将您对 post 实体所做的更改提交到数据库。我不确定在保存/提交评论时它是否也会自动提交帖子。你可以进一步调查的东西。谢谢。
    • 啊,刚看到这个是应该的,因为你设置了cascade = CascadeType.ALL,所以它会自动持久化。所以你是对的,不需要第二次保存
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 2022-01-24
    • 1970-01-01
    • 2017-10-01
    • 2016-01-18
    • 1970-01-01
    • 2016-09-18
    相关资源
    最近更新 更多