Spring Boot MongoDB 分页排序查询实现指南
在 Spring Boot 中使用 MongoDB 实现分页排序查询,可以使用MongoTemplate来实现。
首先,确保你的 Spring Boot 项目中已经引入了spring-boot-starter-data-mongodb依赖。
接下来,创建一个 Repository 接口,继承自MongoRepository,并指定实体类和主键类型。例如:
@Repository
public interface UserRepository extends MongoRepository<User, String> {
// 查询方法
List<User> findByAgeGreaterThan(int age, Pageable pageable);
}
然后,在你的 Service 类中注入UserRepository,并调用相应的查询方法。例如:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getUsersByAge(int age, int pageNo, int pageSize, Sort.Direction direction, String... properties) {
Pageable pageable = PageRequest.of(pageNo, pageSize, direction, properties);
return userRepository.findByAgeGreaterThan(age, pageable);
}
}
在上述代码中,findByAgeGreaterThan方法根据传入的年龄和分页参数来查询用户数据,同时指定了排序的方向和属性。
最后,在 Controller 中使用UserService来处理请求。例如:
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getUsersByAge(@RequestParam int age,
@RequestParam int pageNo,
@RequestParam int pageSize,
@RequestParam(required = false, defaultValue = "ASC") Sort.Direction direction,
@RequestParam(required = false, defaultValue = "id") String... properties) {
return userService.getUsersByAge(age, pageNo, pageSize, direction, properties);
}
}
在上述代码中,getUsersByAge方法根据请求参数来调用UserService中的方法,并返回查询结果。
这样,当你发送GET请求到/users接口时,传入相应的参数,就可以实现分页排序查询了。
原文地址: http://www.cveoy.top/t/topic/qeIN 著作权归作者所有。请勿转载和采集!