我必须实体:
@Data
@Entity
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "article", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Comment> comments;
private String content;
}
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String content;
@ManyToOne(cascade = CascadeType.ALL)
private Article article;
}
一篇文章匹配很多评论。
所以我希望在获取任何文章时,它应该返回当前文章及其注释。
所以我写这个
@Test
public void getArticle(){
article.setComments(comments);
articleRepository.save(article);
System.out.println(JSONObject.toJSONString(article));
// {"comments":[{"content":"还行","id":2},{"content":"不错","id":3}],"content":"这个一篇文章","id":1}
Optional<Article> articleOptional = articleRepository.findById(1L);
System.out.println(JSONObject.toJSONString(articleOptional.get()));
// {"comments":[],"content":"这个一篇文章","id":1}
System.out.println(JSONObject.toJSONString(articleOptional.get().getComments()));
}
如您所见,当我从数据库中获取文章时,当数据库中有两个注释时,我不会返回它的commnets。
如何解决此问题?我想在收到文章时发表评论。