【问题标题】:JPA Join with childEntity.childForeignEntityJPA 加入 childEntity.childForeignEntity
【发布时间】:2021-05-21 19:45:07
【问题描述】:

一个字不知道怎么称呼,我来详细解释一下吧。

假设我的数据库中有以下表/模式:

并相应地遵循以下课程:

1.发帖

@Entity
@Table(name = "posts")
public class Post {
    @Id
    private Long id;

    @Column(name = "text")
    private String text;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "post")
    private Set<PostComment> postComments = new HashSet<>();
}

2.发表评论

@Entity
@Table(name = "post_comments")
public class PostComment {
    @Id
    private Long id;

    @Column(name = "post_id")
    private Long postId;

    @Column(name = "user_id")
    private Long userId;

    @Column(name = "text")
    private String text;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="post_id")
    private Post post;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

3.用户

@Entity
@Table(name = "users")
public class User {
    @Id
    private Long id;

    @Column(name = "some_attributes")
    private String someAttributes;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
    private Set<PostComment> postComments = new HashSet<>();
}

如何通过 PostComment 与用户一起发布帖子,以便在我的帖子实体中获得所有用户的评论:

@Entity
@Table(name = "posts")
public class Post {
    ....
    
    //@ join with post_comments.user_id
    private Set<User> users = new HashSet<>();

    ....
}

【问题讨论】:

    标签: jpa spring-data-jpa persistence


    【解决方案1】:

    好吧,只需获取PostComment.user,其中PostComment.post 等于您的帖子。

    @Query("select pc.user from PostComment pc where pc.post = :post")
    List<User> getUsersWithComments(@Param("post") Post post);
    

    似乎对我有用。给我以下 SQL:

    Hibernate: select user1_.id as id1_2_, user1_.some_attributes as some_att2_2_ from post_comments postcommen0_ inner join users user1_ on postcommen0_.user_id=user1_.id where postcommen0_.post_id=?
    

    我不知道这是怎么回事:

    @Column(name = "post_id")
    private Long postId;
    
    @Column(name = "user_id")
    private Long userId;
    

    或者这个

    @JoinColumn(name="user_id")
    @JoinColumn(name="post_id")
    

    你不应该这样做:

     = new HashSet<>();
    

    虽然我们这样做是多余的。

    fetch = FetchType.LAZY, 
    

    【讨论】:

    • 在实体字段上使用@Query 对我来说至关重要,这可能吗?
    猜你喜欢
    • 2015-10-22
    • 1970-01-01
    • 2020-09-02
    • 2015-10-21
    • 2011-10-17
    • 2013-06-26
    • 2011-04-13
    • 2010-10-02
    • 2013-10-13
    相关资源
    最近更新 更多