1.JpaRepository接口中的主要方式有:
其实很以前的方法一样,我们主要学习一下findAll(Sort sort) 方法
@Test
public void testFindAllSort() {
Order order = new Order(Sort.Direction.DESC, "age");
Sort sort = new Sort(order);
List<Student> sList = studentJpa.findAll(sort);
sList.forEach(System.out::println);
}
2.JpaSpecificationExecutor接口
- 不属于Repository体系,实现一组 JPA Criteria 查询相关的方法
- Specification:封装 JPA Criteria 查询条件。通常使用匿名内部类的方式来创建该接口的对象
在上文的基础上,在继承JpaSpecificationExecutor接口。
其中path的包为:javax.persistence.criteria.Path;
public interface StudentJpa extends JpaRepository<Student, Integer>, JpaSpecificationExecutor<Student>{
}
测试类:
/**
* 1 分页
* 2 排序
* 3 条件查询
*/
@Test
public void testQuery() {
Sort.Order order = new Sort.Order(Sort.Direction.ASC,"id");
Sort sort = new Sort(order);
Pageable pageable = new PageRequest(0, 4,sort);//分页条件
Specification<Student> specification = new Specification<Student>() {
@Override
public Predicate toPredicate(Root<Student> root,
CriteriaQuery<?> query,
CriteriaBuilder cb) {
//root中包含了Student Student包含了score
Path path = root.get("score");
Predicate predicate = cb.gt(path, 5);
return predicate;
}
};
Page<Student> page = studentJpa.findAll(specification, pageable);
System.out.println("查询的总页数"+page.getTotalPages());
System.out.println("查询的总记录数"+page.getTotalElements());
System.out.println("查询的当前第几页"+page.getNumber()+1);
System.out.println("查询的当前页面的集合"+page.getContent());
System.out.println("查询的当前页面的记录数"+page.getNumberOfElements());
}
如果我们想同时搜索多个条件时:
比如搜索年龄19岁且分数为90的人员信息
@Test
public void testQuery() {
Sort.Order order = new Sort.Order(Sort.Direction.ASC,"id");
Sort sort = new Sort(order);
Pageable pageable = new PageRequest(0, 4,sort);//分页条件
Specification<Student> specification = new Specification<Student>() {
@Override
public Predicate toPredicate(Root<Student> root,
CriteriaQuery<?> query,
CriteriaBuilder cb) {
//root中包含了Student Student包含了score
Path path = root.get("score");
Path path1 = root.get("age");
Predicate p1 = cb.equal(path, 90);
Predicate p2 = cb.equal(path1, 18);
return cb.and(p1, p2);
}
};
Page<Student> page = studentJpa.findAll(specification, pageable);
System.out.println("查询的总页数"+page.getTotalPages());
System.out.println("查询的总记录数"+page.getTotalElements());
System.out.println("查询的当前第几页"+page.getNumber()+1);
System.out.println("查询的当前页面的集合"+page.getContent());
System.out.println("查询的当前页面的记录数"+page.getNumberOfElements());
}