在项目中分页查询是一个很常见的场景,通过JPA可以简单的实现分页功能。
首先创建一个接口类,继承 JpaRepository接口。JpaRepository接口中已经继承了分页和排序所需的相关接口PagingAndSortingRepository接口和基本的查询接口QueryByExampleExecutor。
还是以之前的学生类为模板。JpaRepository中第一个类型为数据库映射对应的实体,第二个为数据库表中主键的类型。
public interface StudentJpaRepository extends JpaRepository<StudentEntity, String> {
}
我们想用实现分页查询如下:
@Resource
public class StudentServiceImpl {
private final StudentJpaRepository studentJpaRepository;
public StudentServiceImpl(StudentJpaRepository studentJpaRepository) {
this.studentJpaRepository = studentJpaRepository;
}
public List<StudentEntity> queryPage() {
Page<StudentEntity> page = studentJpaRepository.findAll(PageRequest.of(1, 20));
return page.toList();
}
}
需要注意的是分页查询的起始页签为0,如果需要根据某些字段进行排序的话需要传入Sort类。例如我们需要根据学号进行升序排序的话,可以按照如下方式实现。
@Resource
public class StudentServiceImpl {
private final StudentJpaRepository studentJpaRepository;
public StudentServiceImpl(StudentJpaRepository studentJpaRepository) {
this.studentJpaRepository = studentJpaRepository;
}
public List<StudentEntity> queryPage() {
Sort.TypedSort<StudentEntity> typedSort = Sort.sort(StudentEntity.class);
Sort ascending = typedSort.by(StudentEntity::getStudentId).ascending();
Page<StudentEntity> page = studentJpaRepository.findAll(PageRequest.of(1, 20, ascending));
return page.toList();
}
}
简单的查询就不进行赘述了,实现起来是不是感觉简单很多,而且自动映射为相关的对象,直接就可以进行使用。