springData学习(四)PagingAndSortingRepository接口学习

首先看一下PagingAndSortingRepository接口中的方法,就两个方法

Iterable findAll(Sort sort);和Page findAll(Pageable pageable);

创建一个dao层继承PagingAndSortingRepository

1.分页功能:

测试类:

@Test
	public void testPage() {
		//studentPage
		Pageable pageable = new PageRequest(0, 5);
		Page page = studentPage.findAll(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());
	}

Pageable需要的包为:org.springframework.data.domain下的pageable

2.排序功能:

点击查看PageRequest的源码发现,有一个构造方法可以传入sort来进行排序。

public PageRequest(int page, int size, Sort sort) {

        super(page, size);

        this.sort = sort;
    }

点击查看sort的源码:

有一个参数为Order的构造器,其中Sort.Direction.DESC为排序方法,id以某个字段排序

@Test
	public void testSort() {
		Order order = new Order(Sort.Direction.DESC, "id");
		Sort sort = new Sort(order);
		Pageable pageable = new PageRequest(0, 5, sort);
		Page page = studentPage.findAll(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());
	}

如果我们需要以多个字段同时排序呢?

@Test
	public void testSort() {
		//Order order = new Order(Sort.Direction.DESC, "id");
		String[] array = new String[]{"score","age"};
		Sort sort = new Sort(Sort.Direction.ASC, array);
		Pageable pageable = new PageRequest(5, 5, sort);
		Page page = studentPage.findAll(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());
	}

3.自定义方法

如果我们想对自定义的方法进行分页呢?

dao
@Query("select s from Student s where s.age > :age")
	public Page getDataByAge(Pageable pageable ,Integer age);


测试类:
@Test
	public void testByAge() {
		Pageable pageable = new PageRequest(0, 5);
		Page page = studentPage.getDataByAge(pageable, 20);
		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());
	}

 

你可能感兴趣的:(springData)