FindBy using a foreign key in JPA

joe11093 :

I have the 3 following Entities in my project.

@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 Comment on a particular Review, such that under the page of each Review, I can display the name of the User who 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.

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

Maciej Kowalski :

Use an entity graph in your spring data jpa Repository:

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

or explicitly define a @Query:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=472808&siteId=1