首页 > 解决方案 > Spring Data JPA:如何获取特定类型的所有实体以及每个实体的关联实体?

问题描述

我有一个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 背景,所以起初这有点令人生畏。

标签: springspring-data-jpa

解决方案


您需要做的是从 to 创建双向@OneToMany关联:PostComments

Post在类中添加一个字段

@OneToMany(
        mappedBy = "postId", 
        cascade = CascadeType.ALL
    )
private List<Comments> comments = new ArrayList<>();

从现在开始,当你Post从数据库中获取时,Comments会同时被获取。


推荐阅读