我有以下Springboot代码:
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);
}
}
以及以下亚军:
@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 :(得分:1)
在双向关系中,必须设置关系的两侧;
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