码迷,mamicode.com
首页 > 编程语言 > 详细

SpringData分页功能

时间:2018-10-09 21:49:54      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:content   print   err   one   接口   年龄   roo   表示   实体   

在SpringData中实现分页功能我们需要将接口实现PagingAndSortingRepository这个接口提供了分页查询的方法

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);
        }
    }

这样就可以简单的实现我们的分页了,但是瞬时间发现这个分页并不能带条件啊。

SpringData中给我们提供了一个接口,我们只需要将我们Dao层接口实现JpaSpecificationExecutor就可以达到带条件分页的效果

@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);
    }

SpringData分页功能

标签:content   print   err   one   接口   年龄   roo   表示   实体   

原文地址:https://www.cnblogs.com/SimpleWu/p/9762643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!