【问题标题】:Why i'm getting 'QuerySyntaxException'?为什么我收到“QuerySyntaxException”?
【发布时间】:2020-09-18 00:53:57
【问题描述】:
@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]

【问题讨论】:

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


【解决方案1】:

JPQL 的限制是不行的,我们可以使用 Pageable 来获取基于 order 的记录

    Pageable firstPageWithTwoElements = PageRequest.of(0, 2, Sort.by("id").descending());
    Page<Post> pagedResult = postRepository.findAll(firstPageWithTwoElements);
    List<Post> postList = pagedResult.getContent();

上面的代码将给出最近 2 个根据 ID 排序的条目,

【讨论】:

    猜你喜欢
    • 2017-08-17
    • 2012-05-27
    • 2020-03-09
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多