java FindBy 在 JPA 中使用外键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48122281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:59:36  来源:igfitidea点击:

FindBy using a foreign key in JPA

javaspringjpaormspring-data-jpa

提问by joe11093

I have the 3 following Entities in my project.

我的项目中有以下 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;
}       

I want to use JPA to fetch every Commenton a particular Review, such that under the page of each Review, I can display the name of the Userwho commented, along with the actual Comment. So when I visit the page http://localhost:8080/review/view/5, I want to be able to see the review in addition to all comments made on it, along with the names of the users who added the comments.

我想使用JPA获取每Comment一个特定的Review,使得每个页面下Review,我可以显示的名字User谁评论说,与实际一起Comment。因此,当我访问该页面时http://localhost:8080/review/view/5,除了对其发表的所有评论之外,我还希望能够看到评论,以及添加评论的用户的姓名。

Is this achievable without writing the SQL myself? If yes, how?

这是否可以在不自己编写 SQL 的情况下实现?如果是,如何?

回答by Maciej Kowalski

Use an entity graph in your spring data jpa Repository:

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

@EntityGraph(value = "Review.comments", type = EntityGraphType.FETCH)
public Review findByReviewId(int id);

or explicitly define a @Query:

或者明确定义一个@Query:

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