父实体:
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;
}
现在帖子实体将包含作者的映射,我试图根据浏览次数从帖子中仅获取作者
我厌倦了下面的查询,不知道如何得到
@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);
最佳答案
@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);
使用公共(public) ID 连接父级和子级,并根据 View 进行排序
关于java - 如何从 JPA 中的父实体检索子数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62210838/