This article brings you an introduction to the method of implementing paging function in SpringData. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
To implement the paging function in SpringData we need to implement the interface PagingAndSortingRepositoryThis interface provides a method of paging query
Page<T> findAll(Pageable pageable); //分页查询(含排序功能)
@Test public void Pagination() { int pageIndex = 1;// 前台传过来的当前页 int pageSize = 5;// 每页需要的记录数 /** * 不带排序写法: Pageable pageable = new PageRequest(pageIndex, pageSize); */ // 按照年龄字段排序 Order order = new Order(Direction.DESC, "age"); Sort sort = new Sort(order); Pageable pageable = new PageRequest(pageIndex - 1, pageSize, sort); Page<Student> page = studentService.findAll(pageable); System.out.println("总记录数:" + page.getTotalElements()); System.out.println("当前第几页:" + (page.getNumber() + 1)); System.out.println("总页数:" + page.getTotalPages()); System.out.println("当前页的List:" + page.getContent()); System.out.println("当前页面的记录数:" + page.getNumberOfElements()); for (Student student : page.getContent()) { System.out.println(student); } }
This way we can easily implement our paging, but we instantly discovered that this paging does not have conditions.
SpringData provides us with an interface. We only need to implement our Dao layer interfaceJpaSpecificationExecutor to achieve the effect of conditional paging
@Test public void testJpaSpecificationExecutor(){ int pageIndex = 1; int pagesize = 0; PageRequest pagerequest = new PageRequest(pageIndex - 1, pagesize); Specification<Student> specification = new Specification<Student>() { @Override public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) { /** * Root<Student>:表示查询的实体 * CriteriaQuery:可以从中得到root对象,即告知JPA criteria查询要查询哪一个实体类。还可以来添加查询条件。还可以结合EntityManager对象得到最终查询的TypedQuery对象。 * CriteriaBuilder:用于创建Criteria相关对象的工厂。 */ //年龄属性 Path<Integer> path = root.get("age"); Predicate predicate = cb.gt(path, 5);//大于5 return predicate; } }; Page<Student> page = studentDao.findAll(specification, pagerequest); }
The above is the detailed content of Introduction to the method of implementing paging function in SpringData. For more information, please follow other related articles on the PHP Chinese website!