代码之家  ›  专栏  ›  技术社区  ›  MrD

SpringBoot父子关系

  •  0
  • MrD  · 技术社区  · 7 年前

    注释.java

    @Entity
    @Getter @Setter @NoArgsConstructor @RequiredArgsConstructor
    public class Comment extends Auditable {
    
        @Id
        @GeneratedValue
        private Long id;
    
        @NonNull
        private String comment;
    
        @ManyToOne(fetch = FetchType.LAZY)
        private Link link;
    }
    

    链接.java

    @Entity
    @Getter @Setter @NoArgsConstructor @RequiredArgsConstructor
    public class Link extends Auditable {
    
        @Id
        @GeneratedValue
        private Long id;
    
        @NonNull
        private String title;
    
        @NonNull
        private String url;
    
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "link")
        private List<Comment> comments = new ArrayList<>();
    
        public void addComment(Comment c) {
            comments.add(c);
        }
    }
    

    以及以下跑步者:

     @Bean
     CommandLineRunner someRunner(LinkRepository lr, CommentRepository cr) {
         return args -> {
             Link link = new Link("Getting started", "url");
             Comment c = new Comment("Hello!");
             link.addComment(c);
             linkRepository.save(link);
         };
     };
    

    我正在尝试将评论链接到链接,并将两者保存在一起。但是,这是输出:

    [
        {
            createdBy: null,
            createdDate: "2/28/19, 11:48 PM",
            lastModifiedBy: null,
            lastModifiedDate: "2/28/19, 11:48 PM",
            id: 2,
            comment: "Hello!",
            link: null
        }
    ]
    

    关于如何让链接真正显示在链接列表中,有什么建议吗?

    0 回复  |  直到 7 年前
        1
  •  1
  •   buræquete Naveen Kocherla    7 年前

    在双向关系中,必须设置关系的双方;

    Link link = new Link("Getting started", "url");
    Comment comment = new Comment("Hello!");
    comment.setLink(link);  // missing in your code
    link.addComment(comment);
    linkRepository.save(link);
    

    “检查” 双向多对一关联 “>”; here