本篇文章给大家带来的内容是关于springdata中实现分页功能的方法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
在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中实现分页功能的方法介绍的详细内容。