Почему я получаю QuerySyntaxException? - PullRequest
0 голосов
/ 30 мая 2020
@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]

1 Ответ

0 голосов
/ 03 июня 2020

Лимит не будет работать JPQL, мы можем использовать Pageable для получения записей на основе порядка

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

приведенный выше код даст последние 2 записи, отсортированные по идентификатору,

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...