SpringBoot操作MongoDB实现分页查询 不念不忘少年蓝@ 2022-08-23 00:40 685阅读 0赞 前几天写了一篇关于介绍SpringBoot的简单使用。以及使用SpringBoot JPA做了一次数据库的一个CURD (地址:[http://blog.csdn.net/canot/article/details/51449589][http_blog.csdn.net_canot_article_details_51449589])这篇文件简单学习Spring Boot JPA 或者说是Spring Data对现在很流行的一个nosql产品MongoDB的简单操作(主要针对在分页查询上)。 于前面SpringBoot的HelloWorld类似,在导入必要的核心包之后,为了正常驱动MongoDB还需要额外的包(MongoDB驱动包): <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.2.2</version> </dependency> 在之前的Spring Boot的演示中,为了使得项目能够正确的驱动数据库。必须在项目的根目录下增加了一个配置文件:application.properties.该配置文件写入了数据库的信息,如操作哪个数据库,帐号密码等等。在操作MongoDB中这个文件不是必须的了。当你的数据库没有设置帐号密码时,当你要操作的集合位于数据库test中时,这个配置文件可以省掉。当如果不是上述的情况那么一定需要该配置文件: spring.data.mongodb.database: ticket spring.data.mongodb.uri: mongodb://localhost:27017 //xxxx Dao接口: @Repository public interface CustomerDao extends PagingAndSortingRepository<Customer,String>{ } 实体类: //指定对应于集合customer @Document(collection = "customer") public class Customer { //主键 @Id private String _id; private String name; private String phone; private String gender; private String birthday; private String passport; //xxxx } Controller层: @Autowired CustomerDao customerDao; //完成分页请求 @RequestMapping("/selectName") public List<Customer> selectName(@RequestParam("id") int id){ //构建分页信息 PageRequest pageRequest = buildPageRequest(id,5,null); //查询指定分页的内容 Iterator<Customer> customers = customerDao.findAll(pageRequest).iterator(); List<Customer> lists = new ArrayList<Customer>(); while(customers.hasNext()){ lists.add(customers.next()); } return lists; } /** * * 创建分页请求. */ private PageRequest buildPageRequest(int pageNumber, int pageSize,String sortType) { Sort sort = null; if ("auto".equals(sortType)) { sort = new Sort(Direction.DESC, "id"); } else if ("birthday".equals(sortType)) { sort = new Sort(Direction.ASC, "birthday"); } //参数1表示当前第几页,参数2表示每页的大小,参数3表示排序 return new PageRequest(pageNumber-1,pageSize,sort); } Spring Boot 或者Spring data提供给我们的接口形式来帮我们来完成对于表的CRUR操作。那么我们了来思考怎么实现对于某个字段的查询,在以前我们自己手写的DAO中我们通过编写一个findByxxx来实现,在Spring Boot或者说Spring Data中它也为我们提供了这种方法,并且我们也只需要写在接口中,而不需要实现类,它就能帮我们实现。 **查询所有性别为男,并按生日排序** @Repository public interface CustomerDao extends PagingAndSortingRepository<Customer,String>{ //这个方法名不能乱写,findByXXX,那么对于的类中必须有XXX字段。也就是说对应的数据库中一定要存在XXX字段对应的列 public Page<Customer> findBygender(String gender,Pageable pageable); } **这里注意一点,虽然我们在调用Repository方法中的分页查询时,传入的参数是PageRequest。但一定要在Repository定义该方法时参数定义为Pageable。否则会报错:Paging query needs to have a Pageable parameter** Controller: @RequestMapping("/selectBygender") public Page<Customer> getBygender(String gender,@RequestParam("pageNumber") int pageNumber){ //构建分页信息 PageRequest pageRequest = buildPageRequest(pageNumber,5,"birthday"); Page<Customer> customera = customerDao.findBygender(gender,pageRequest); return customers; } [http_blog.csdn.net_canot_article_details_51449589]: http://blog.csdn.net/canot/article/details/51449589
还没有评论,来说两句吧...