SpringJPA是使用PageRequest
来进行分页查询的,PageRequest
有三个构造方法,
并且排序的页码是从零开始的。
//单纯根据页码和页码大小
public PageRequest(int page, int size) {
this(page, size, (Sort)null);
}
//直接根据Direction 和字段名进行排序
public PageRequest(int page, int size, Direction direction, String... properties) {
this(page, size, new Sort(direction, properties));
}
//根据sort对象进行排序
public PageRequest(int page, int size, Sort sort) {
super(page, size);
this.sort = sort;
}
例子
//单纯根据页码和页码大小
Pageable pageable = new PageRequest(page,pageSize);
//直接根据Direction 和字段名进行排序
Pageable pageable=new PageRequest(page, pageSize,Sort.Direction.DESC,"createDate");
//根据sort对象进行排序
Sort sort = new Sort(Sort.Direction.DESC,"createDate");
Pageable pageable = new PageRequest(page,pageSize,sort);
TestReposity.findAll(pageable);
模糊查询需要Repository
接口继承JpaSpecificationExecutor
接口。
public interface TestRepository extends JpaRepository<Student, Integer>,JpaSpecificationExecutor<Student>{
使用 JpaSpecificationExecutor
的Page
构造方法
Page pageWebSite=StudentRepository.findAll(new Specification() {
@Override
public Predicate toPredicate(Root root, CriteriaQuery> query, CriteriaBuilder cb) {
Predicate predicate=cb.conjunction();
if(student!=null){
if(StringUtil.isNotEmpty(student.getName())){
predicate.getExpressions().add(cb.like(root.get("name"), "%"+student.getName().trim()+"%"));
}
if(student.getAge()!=null && student.getAge()>1){
predicate.getExpressions().add(cb.equal(root.get("age"), student.getAge()));
}
}
return predicate;
}
}, pageable);
return pageWebSite.getContent();
}
在Repository接口中写
@Query(value="SELECT * FROM student WHERE score1 ORDER BY id DESC LIMIT 1",nativeQuery=true)
public Student getScoreLowerStudent(Integer score);