且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据spring jpa中的实体从多个表中获取数据

更新时间:2023-01-21 11:53:03

由于您的代码包含 spring-boot spring-jpa

我假设您可以使用弹簧数据存储库

Since your tags include spring-boot and spring-jpa.
I assume you can use spring data repositories

发布的实体不以任何方式关联。因此,必须关联实体才能使用一个存储库检索所有数据
实体的修改版本如下所示:

The entities posted are not associated in any way. Therefore, the entities must be associated in order to retrieve all the data with one repository The modified version of entities look like this:

注释表

@Entity
@Table(name = "comments")
public class CommentBean implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "commentId")
    private long commentId;

    @ManyToOne
    @JoinColumn(name="topicId")
    private TopicBean topicBean;

    @OneToMany(mappedBy="commentBean")
    private List<CommentLikes> commentLikesList;
}

主题表

@Entity
@Table(name = "topics")
public class TopicBean implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "topicId")
    private String topicId;
    @Column(name = "title")
    private String title;
    @Column(name = "details")
    private String details;
    @Column(name = "username")
    private String username;
    @Column(name = "userImage")
    private String userImage;
    @Column(name = "dayPosted")
    private String dayPosted;

    @OneToMany(mappedBy="topicBean")
    private List<CommentBean> commentBeans;
}

comment_likes table

comment_likes table

@Entity
@Table(name = "comment_likes")
public class CommentLikes implements Serializable {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

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

    @ManyToOne
    @JoinColumn(name="commentId")
    private CommentBean commentBean;
}  

请注意,上述重写基于我可以做出的最明智的猜测到原始实体。

Note that the above rewrite is based on the most sensible guess I can make according to the original entities.

现在三个实体正确关联。
您可以使用TopicBean存储库来检索所有TopicBeans,另外两个也将被检索。

topicBeanRepo.findAll()

Now the three entities are properly associated. You can just use TopicBean repository to retrieve all the TopicBeans and the other two will be retrieved as well.
topicBeanRepo.findAll()