gpt4 book ai didi

java - FindBy 在 JPA 中使用外键

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:38:56 29 4
gpt4 key购买 nike

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

我想使用 JPA 获取特定 Review 上的每个 Comment,这样在每个 Review 的页面下,我可以显示发表评论的 User 的名称,以及实际的 Comment。因此,当我访问页面 http://localhost:8080/review/view/5 时,我希望能够看到评论以及对它所做的所有评论,以及添加评论的用户。

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

最佳答案

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

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

或者显式定义一个@Query:

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

关于java - FindBy 在 JPA 中使用外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48122281/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com