您的位置:首页 > 编程语言 > ASP

jpa学习5--spring data jpa 中的JpaSpecificationExecutor和PagingAndSortingRepository分页

2017-03-05 20:02 471 查看
 jpa学习5--spring data jpa 中的JpaSpecificationExecutor和PagingAndSortingRepository分页
1.继承JpaSpecificationExecutor分页:
/**
* 目标: 实现带查询条件的分页. id > 5 的条件
*
* 调用 JpaSpecificationExecutor 的 Page<T> findAll(Specification<T> spec, Pageable pageable);
* Specification: 封装了 JPA Criteria 查询的查询条件
* Pageable: 封装了请求分页的信息: 例如 pageNo, pageSize, Sort
int pageSize = 5;
*/
@Test
public void testJpaSpecificationExecutor(){
int pageNo = 3 - 1;
Specification<Person> specification = new Specification<Person>() {
PageRequest pageable = new PageRequest(pageNo, pageSize);

//通常使用 Specification 的匿名内部类
/**
* @param *root: 代表查询的实体类.
* @param *cb: CriteriaBuilder 对象. 用于创建 Criteria 相关对象的工厂. 当然可以从中获取到 Predicate 对象
* @param query: 可以从中可到 Root 对象, 即告知 JPA Criteria 查询要查询哪一个实体类. 还可以
* 来添加查询条件, 还可以结合 EntityManager 对象得到最终查询的 TypedQuery 对象.
* @return: *Predicate 类型, 代表一个查询条件.
*/
@Override
}
public Predicate toPredicate(Root<Person> root,
CriteriaQuery<?> query, CriteriaBuilder cb) {
Path path = root.get("id");
Predicate predicate = cb.gt(path, 5);
return predicate;
};

System.out.println("总页数: " + page.getTotalPages());
Page<Person> page = personRepsotory.findAll(specification, pageable);

System.out.println("总记录数: " + page.getTotalElements());
System.out.println("当前第几页: " + (page.getNumber() + 1));
System.out.println("当前页面的 List: " + page.getContent());
}
System.out.println("当前页面的记录数: " + page.getNumberOfElements());


2.PagingAndSortingRepository
•该接口提供了分页与排序功能
–Iterable<T>findAll(Sortsort); //排序
–Page<T> findAll(Pageablepageable);//分页查询(含排序功能) 

public void testPagingAndSortingRespository(){
//pageNo 从 0 开始.
int pageNo = 6 - 1;
int pageSize = 5;
//Pageable 接口通常使用的其 PageRequest 实现类. 其中封装了需要分页的信息
//排序相关的. Sort 封装了排序的信息
//Order 是具体针对于某一个属性进行升序还是降序.
Order order1 = new Order(Direction.DESC, "id");
Order order2 = new Order(Direction.ASC, "email");
Sort sort = new Sort(order1, order2);

PageRequest pageable = new PageRequest(pageNo, pageSize, sort);
Page<Person> page = personRepsotory.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());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: