[Java Spring data] Paging and sorting

package com.example.university.repo;

import com.example.university.domain.Staff;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface StaffRepository extends PagingAndSortingRepository<Staff,Integer> {
}
public interface CourseRepository extends CrudRepository<Course,Integer>{

    List<Course> findByCredits(@Param("credits") int credits);

    Page<Course> findByCredits(@Param("credits") int credits, Pageable pageable);

}

 

Usage:

    @Test
    public void pagingAndSortingQueries() {
        System.out.println("\nFind all 3-credit courses");
        courseRepository.findByCredits(3).forEach(System.out::println);

        System.out.println("\nFind first 4 3-credit courses, sort by credit, then course name");
        Page<Course> courses = courseRepository.findByCredits(3,
                PageRequest.of(0, 4, Sort.Direction.ASC, "credits", "name"));
        courses.forEach(System.out::println);

        System.out.println("\nFind all staff members, sort alphabetically by last name");
        Sort sortByLastName = new Sort(Sort.Direction.ASC, "member.lastName");
        staffRepository.findAll(sortByLastName).forEach(System.out::println);

        Page<Staff> members = staffRepository.findAll(PageRequest.of(0, 5, sortByLastName));
        System.out.println("\nTotal number of staff members=" + members.getTotalElements());
        System.out.println("Total number of 5-element-pages=" + members.getTotalPages());
        System.out.println("Find first 5 Staff members, sort alphabetically by last name");
        members.forEach(System.out::println);
    }

  

posted @ 2020-12-18 04:20  Zhentiw  阅读(116)  评论(0编辑  收藏  举报