在spring boot中实现rest接口的分页查询,最直接的做法是定义一个接收pageable参数的控制器方法,并在service层使用jparepository的findall(pageable)方法。这样框架会自动解析请求中的页码和大小参数,返回包含数据和总条数的page对象。需要注意的是,如果前端传递了不支持的排序字段,默认行为会抛出异常,因此建议显式配置允许的排序属性。

如何定义支持分页的Controller接口
通过让Controller方法的参数直接声明为Pageable类型,Spring MVC会自动将URL中的page、size和sort参数绑定到该对象上。这种方法无需手动解析Query String,且能直接传递给Repository层。为了安全起见,通常会在方法签名中结合@Validated来限制排序字段的范围,防止非法查询。

import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping public Page<User> getUsers(Pageable pageable) { return userService.findAll(pageable); } }上述代码展示了最基础的Controller结构。当请求/api/users?page=0&size=10时,userService.findAll会接收到对应的分页对象并执行查询。返回的Page<user></user>对象会自动序列化为JSON,包含内容列表和元数据。开发者只需关注业务逻辑,无需处理分页计算细节。
Service层如何配合Repository进行查询
Service层主要负责调用Repository的分页方法,并可选地添加业务过滤条件。如果使用Spring Data JPA,Repository接口继承自JpaRepository即可直接使用内置的分页功能。若需根据特定条件(如用户名)过滤,可定义自定义查询方法,该方法同样接受Pageable作为最后一个参数,框架会自动拼接分页逻辑。

import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public Page<User> findAll(Pageable pageable) { return userRepository.findAll(pageable); } public Page<User> findByUsername(String username, Pageable pageable) { return userRepository.findByUsername(username, pageable); } }在Service实现中,findByUsername方法演示了带条件的分页查询。Repository接口中需要定义对应的方法签名:Page<user> findByUsername(String username, Pageable pageable)</user>。Spring Data会根据方法名自动生成SQL,并在末尾追加LIMIT和OFFSET子句。这种组合方式既保证了分页效率,又满足了复杂查询需求。
如何处理前端传入的空值或默认排序
当用户未指定排序规则时,Pageable默认为空排序,此时数据库可能按主键或其他隐式顺序返回结果,导致分页不稳定。为确保每次查询结果一致,应在Service层或Repository层提供默认的排序策略。例如,强制按创建时间倒序排列,这样可以保证最新的数据始终排在前面,且分页游标稳定。


















