【问题标题】:FindBy using a foreign key in JPAFindBy 在 JPA 中使用外键
【发布时间】:2018-06-15 18:40:41
【问题描述】:

我的项目中有以下 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 的名称以及实际的@ 987654326@。因此,当我访问页面http://localhost:8080/review/view/5 时,我希望能够看到评论以及在其上所做的所有 cmets,以及添加 cmets 的用户的姓名。

不自己编写 SQL 可以实现吗?如果是,怎么做?

【问题讨论】:

  • 如果您有一个Review 对象,Review.comments 立即为您提供与该对象关联的所有Comments,Comment.user 为您提供与每个评论相关联的User。因此,鉴于您的实体包含正确的关联,目前尚不清楚您是否难以找到用于评论的 cmets 或用于评论的用户,以及原因。

标签: java spring jpa orm spring-data-jpa


【解决方案1】:

在您的 spring data jpa Repository 中使用实体图:

@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);

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 2020-06-22
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    相关资源
    最近更新 更多