@Query("SELECT new com.ethihas.v1.blog.dto.PostDto(p.title, p.image, p.content, p.location,p.city, p.state, p.country) FROM Post p order by id desc limit 10")
List<PostDto> getAllPosts(@Param("from") Integer from, @Param("to") Integer to);
上面是我的查询,下面是PostDto的构造函数
public PostDto(String title, Integer image, String content, String location, String city, String state, String country) {
this.title = title;
this.image = image;
this.content = content;
this.location = location;
this.city = city;
this.state = state;
this.country = country;
}
所有内容仅对我来说不错,但导致以下异常
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: limit near line 1, column 167 [SELECT new com.ethihas.v1.blog.dto.PostDto(p.title, p.image, p.content, p.location,p.city, p.state, p.country) FROM com.ethihas.v1.blog.model.Post p order by id desc limit 10]
限制将不适用于JPQL,我们可以使用Pageable根据订单获取记录
Pageable firstPageWithTwoElements = PageRequest.of(0, 2, Sort.by("id").descending());
Page<Post> pagedResult = postRepository.findAll(firstPageWithTwoElements);
List<Post> postList = pagedResult.getContent();
上面的代码将根据ID对最近的2个条目进行排序,