在JPA中使用外键进行FindBy

joe*_*093 3 java orm spring jpa spring-data-jpa

我的项目中有以下3个实体。

@Entity
public class Review {
    @Id
    @GeneratedValue
    private int reviewId;

    @OneToMany(mappedBy="review", cascade = CascadeType.ALL)
    private List<Comment> comments;

    @ManyToOne
    private User user;
}

@Entity
public class Comment {
    @Id
    @GeneratedValue
    private int commentId;

    @ManyToOne
    private Review review;

    @ManyToOne
    private User user;
}

@Entity
public class User {
    @Id @GeneratedValue
    private Long userId;

    @OneToMany(mappedBy="user", cascade = CascadeType.ALL)
    private List<Comment> comments;

    @OneToMany(mappedBy="user", cascade = CascadeType.ALL)
    private List<Review> reviews;
}       
Run Code Online (Sandbox Code Playgroud)

我想使用JPA来获取Comment特定内容上的所有内容Review,以便在每个页面的下方Review显示User实际评论的评论者的姓名Comment。因此,当我访问该页面时http://localhost:8080/review/view/5,除了其上进行的所有评论之外,我还希望能够看到该评论以及添加评论的用户的姓名。

无需自己编写SQL即可实现吗?如果是,怎么办?

Mac*_*ski 6

在spring数据jpa存储库中使用实体图:

@EntityGraph(value = "Review.comments", type = EntityGraphType.FETCH)
public Review findByReviewId(int id);
Run Code Online (Sandbox Code Playgroud)

或显式定义@Query:

@Query("from Review r inner join fetch r.comments where r.reviewId = :id")
User findByReviewId(@Param("id") int id);
Run Code Online (Sandbox Code Playgroud)