繁体   English   中英

JPA 加入 childEntity.childForeignEntity

[英]JPA Join with childEntity.childForeignEntity

我不知道它是如何一言以蔽之的,但让我详细解释一下。

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

数据库样本

并相应地遵循以下课程:

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 与用户一起加入 Post,因此在我的 Post 实体中,我可以获得所有用户的评论:

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

    ....
}

好吧,只需获取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, 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM