MrD
MrD

Reputation: 5084

SpringBoot Parent-Child Relation

I have the following Springboot code:

Comment.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;
}

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);
    }
}

And the following Runner:

 @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);
     };
 };

I am trying for the comment to be linked to the link, and both to save together. However, this is the output:

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

Any advice on how I can get the link to actually show in the list of links?

Upvotes: 2

Views: 1052

Answers (1)

bur&#230;quete
bur&#230;quete

Reputation: 14698

In a bidirectional relationship, you have to set both sides of the relationship;

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);

Check "Bidirectional Many-to-One Associations" > here

Upvotes: 2

Related Questions