Spring 数据@Query,具有可分页和排序不排序



我正在尝试指定一个用@Query注释的存储库方法和一个内部带有Sort对象的可分页:

编辑 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。

你可以这样做,就像我一样。

试试这个,它可以帮你一点点。

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 boot排序可分页"时,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=,其中方向由属性名称的附加逗号提供。

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

{"content":

[],"last":true,"totalElements":0,"totalPages":0,"sort":[{"direction":"DESC","property":"createdDate","ignoreCase":false,"nullHandling":"NATIVE","升序":false,"降序":true}],"size":1000,"number":0,"first":true,"numberOfElements":0}(

我希望这有所帮助。

最新更新