← 返回首页
SpringBoot基础教程(十八)
发表时间:2020-10-26 11:55:49
PagingAndSortingRepository

PagingAndSortingRepository继承自 CrudRepository 接口,提供了排序以及分页查询能力,提供了两个方法:

Iterable<T> findAll(Sort var1);
Page<T> findAll(Pageable var1);

其中,第二个方法finaAll(Pageable var1)可以很轻松的实现分页查询功能。 Pageable 是一个接口,提供了分页一组方法的声明,如第几页,每页多少条记录,排序信息等。PageRequest是 Pageable 的实现类,提供了PageRequest.of(int page, int size, Direction direction, String... properties)静态方法返回一个Pageable 实例。

分页实例

1.定义StudentsRepository

public interface StudentsRepository extends JpaRepository<Students,Integer> {

}

2.在Service层定义实现分页查询的方法。

public interface StudentsService {
    //分页查询
    Page<Students> findAllByPager(Pageable pageable);
}

3.在实现层调用PagingAndSortingRepository接口的findAll方法

@Service
public class StudentsServiceImpl implements StudentsService {

    @Resource
    private StudentsRepository studentsRepository;

    @Override
    Page<T> findAllByPager(Pageable pageable){
         return studentsRepository.findAll(pageable);
    }

}

4.编写测试类,测试分页效果。

@RunWith(SpringRunner.class)//指定Junit4使用Spring提供的测试环境
@SpringBootTest
public class StudentsServiceTest {
    @Resource
    private StudentsService studentsService;

    //实现学生资料的分页查询
    @Test
    public void testQueryStudentsPager(){
        Sort.Direction sort = Sort.Direction.DESC;//默认是降序排序
        //查询第一页(序号从0开始),每页2条记录,默认奖项排序,排序字段是"sid"
        Pageable pager = PageRequest.of(0,2,sort,"sid");

        Page<Students> page = studentsService.findAllByPager(pager);
        List<Students> studentsList = page.getContent();
        for(Students s: studentsList){
            System.out.println(s);
        }
    }
}