如何从JPA中的父实体检索子数据

时间:2020-06-05 08:07:58

标签: java mysql spring spring-boot spring-data-jpa

ParentEntity:

 public class Post {
        @Id
        @GeneratedValue(strategy= GenerationType.AUTO)
        private Integer id;

        private String title;

        private Integer image;

        private Integer views;

        @OneToOne
        private Author author;
    }

子实体

    public class Author{
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Integer id;

    private String name;

    private String bio;
}

现在Post实体将包含Author的映射,我正尝试根据视图数仅从post中获取Authors

我对以下查询感到厌倦,不确定如何获得

@Query(value = "SELECT new com.demo.v1.blog.dto.AuthorDto(p.author.id,a.name,p.author.bio,p.author.image,p.author.isDeleted,p.author.status,p.author.postsNum) FROM Post p order by views DESC")
Page<AuthorDto> getAuthorsByViews(Pageable pageable);

1 个答案:

答案 0 :(得分:0)

    @Query(value = "SELECT new com.demo.v1.blog.dto.AuthorDto(a.id,a.name,a.bio,a.image,a.isDeleted,a.status,a.postsNum) FROM Author a INNER JOIN Post p on a.id = p.author GROUP BY p.author order by p.views DESC")
Page<AuthorDto> getAuthorsByViews(Pageable pageable);

加入具有共同ID的父级和子级,并根据视图进行排序