Spring Boot 3.2.2分页排序:如何让初始数据默认按Id降序?
解决Spring Boot分页初始默认按Id降序且保留自定义排序的问题
问题原因
你之前添加的findAllByOrderByIdDesc(Pageable pageable)方法会强制使用方法名中定义的id DESC排序,忽略Pageable参数中的排序规则,所以当传入自定义的sortField和sortDirection时,排序功能失效。
解决方案
在服务层动态生成Sort规则:优先使用传入的排序参数,若未传入(初始状态)则默认按Id降序排序,继续使用原生的findAll(pageable)方法即可,无需修改Repository。
修改后的服务层代码
import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.util.StringUtils; public Page<Person> getPage(int pageNo, int pageSize, String sortField, String sortDirection) { // 确定排序字段:有传入有效参数则用传入值,否则默认id String targetSortField = StringUtils.hasText(sortField) ? sortField : "id"; // 确定排序方向:有传入有效参数则转成枚举,否则默认降序 Sort.Direction targetSortDir = StringUtils.hasText(sortDirection) ? Sort.Direction.valueOf(sortDirection.toUpperCase()) : Sort.Direction.DESC; Sort sortOption = Sort.by(targetSortDir, targetSortField); Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sortOption); return this.personRepository.findAll(pageable); }
代码说明
- 用
StringUtils.hasText()判断传入的排序参数是否有效(非空且非空白字符串) - 参数无效时自动切换到默认的
id DESC排序逻辑 - 保留原生
findAll(pageable)方法,确保分页和自定义排序功能同时生效
补充优化(可选)
如果是接口层接收参数,可以结合@RequestParam设置默认值,让参数传递更灵活:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @GetMapping("/persons") public Page<Person> getPage( @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10") int pageSize, @RequestParam(required = false) String sortField, @RequestParam(required = false) String sortDirection) { // 同上排序逻辑代码 }
内容的提问来源于stack exchange,提问作者Bill D.
相关产品推荐
相关产品推荐

