我有一个Post
实体
@Entity
public class Post {
@Id
private UUID id;
@NotNull
private String title;
@NotNull
private String content;
@NotNull
private String identifier;
@NotNull
private String category;
@NotNull
@Column(name = "created_at")
private Date createdAt;
@NotNull
@Column(name = "updated_at")
private Date updatedAt;
public Post (){
}
public Post (String title, String content, String category){
this.title = title;
this.content = content;
this.category = category;
}
// rest of the getters and setters
}
这是我的Comment
实体:
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private UUID id;
@NotNull
private String name;
@NotNull
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer identifier;
@NotNull
private String email;
@NotNull
private String content;
@NotNull
@ManyToOne
@JoinColumn(name = "post_id")
private Post postId;
@NotNull
@Column(name = "created_at")
private Date createdAt;
public Comment() {
}
public Comment(String name, String email, String content){
this.name = name;
this.email = email;
this.content = content;
}
}
这是我的帖子控制器:
@RestController
@RequestMapping("/posts")
public class PostController {
private String getIdentifier(String str){
return String.join("-", str.split(" "));
}
@Autowired
private PostService postService;
@RequestMapping(value = "", method = {GET, HEAD})
public List<Post> getAllPosts(){
return postService.getAllPosts();
}
@RequestMapping(value = "", method = {POST, OPTIONS})
public Post addNewPost(@RequestBody Post post){
post.setId(UUID.randomUUID());
post.setIdentifier(this.getIdentifier(post.getTitle()));
post.setCreatedAt(new Date());
post.setUpdatedAt(new Date());
return postService.savePost(post);
}
@RequestMapping(value = "/{id}", method = {GET, HEAD})
public Post getOnePost(@PathVariable UUID id){
return postService.getOne(id);
}
@RequestMapping(value = "/{id}", method = DELETE)
public void deleteOnePost(@PathVariable UUID id){
postService.deleteOnePost(id);
}
}
我的问题是,每当我抓取所有帖子时,如何获取每封帖子的所有评论?
抱歉,我来自NoSQL背景,所以一开始这有点令人生畏。
答案 0 :(得分:1)
您需要做的是创建从setting.$"Domain{numberofDomain}{i}AttributeId"
到@OneToMany
的双向Post
关联:
在Comments
类
Post
从现在开始,当您从数据库中获取@OneToMany(
mappedBy = "postId",
cascade = CascadeType.ALL
)
private List<Comments> comments = new ArrayList<>();
时,将同时提取Post
。