【问题标题】:Spring Data @Query with Pageable and Sort not sortingSpring Data @Query with Pageable and Sort 不排序
【发布时间】:2019-02-08 00:37:06
【问题描述】:

我正在尝试指定一个带有 @Query 注释的存储库方法和一个带有 Sort 对象的 Pageable:

编辑 1:此存储库正在扩展 PagingAndSortingRepository

@Query("...")
Page<Entity> findBySomething(..., Pageable pageable);

pageable 对象是使用以下方法签名指定的:

public PageRequest(int page, int size, Direction direction, String... properties)

但是生成的输出查询没有排序选项,例如:

select a, b, c from table_x where ... limit 10

...虽然我期待的是:

select a, b, c from table_x where ... order by a asc limit 10

这里有人遇到过这种问题吗? 我正在使用 Spring-Boot 1.5.x。

【问题讨论】:

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


    【解决方案1】:

    你可以像我一样做到这一点。

    试试这个,对你的帮助不大。

    1) 在控制器中

    @RequestMapping("/findUserByNameAndSortItDescNo/{name}")
    public @ResponseBody Page<User> findBookByNameAndSortItAscByName(
            @PathVariable String name) {
        // Page = 'A page is a sublist of a list of objects. 
        // It allows gain information about the position of it in the
        // containing entire list.'
        Page<User> user = userRepository.findByName(
           name, 
           new PageRequest(0,100,new Sort(Direction.DESC,"no")));
    
        return user;
    }
    

    2) 在存储库中。

    Page<User> findByName(String name,Pageable pageable);
    

    【讨论】:

    • 哪一个?查找姓名?对于这种方法,spring-data-jpa 将创建一个隐式的 hql 查询,不需要 @Query 注释。
    • 我的意思是我不能使用由 Spring-Data 生成的名称查询,
    【解决方案2】:

    您的请求是什么样的?

    不幸的是,当您搜索“spring boot sort pageable”时,Google 上有一个高索引页面,它指向您:
    https://docs.spring.io/spring-data/rest/docs/2.0.0.M1/reference/html/paging-chapter.html

    以上方法不再是正确的排序方式。你应该关注这个https://docs.spring.io/spring-data/rest/docs/current/reference/html/

    旧的排序方式是添加一个附加的参数,该参数具有相同的名称,后缀为“.dir”,带有 asc 或 desc。

    新方法是 &sort=,其中方向由属性名称的附加逗号提供。

    您还可以查看返回结果的“排序”值,以查看在检查后端查询生成之前是否尝试过排序。即

    {"content":[],"last":true,"totalElements":0,"totalPages":0,"sort":[{"direction":"DESC","property":"createdDate" ,"ignoreCase":false,"nullHandling":"NATIVE","ascending":false,"descending":true}],"size":1000,"number":0,"first":true,"numberOfElements" :0})

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-09-18
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      相关资源
      最近更新 更多