使用jpa如何写分页查询
时间: 2024-05-22 08:13:34 浏览: 11
使用 JPA 实现分页查询非常简单,只需使用 Spring Data 提供的分页接口即可。具体步骤如下:
1. 定义 DAO 接口并继承 JpaRepository 或者 PagingAndSortingRepository 接口,例如:
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {}
2. 在 Service 层中使用 Pageable 接口控制分页,例如:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page<UserEntity> getUserList(Integer pageNum, Integer pageSize) {
Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
return userRepository.findAll(pageable);
}
}
3. 在 Controller 层中接收分页参数并调用 Service 层中的方法,例如:
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user")
public Page<UserEntity> getUserList(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
return userService.getUserList(pageNum, pageSize);
}
}
这样就可以通过 GET 请求获取指定页码的用户列表了。