咱們能夠看到,BlogRepository
定義了這樣一個方法:Page<Blog> findByDeletedFalse(Pageable pageable);
,咱們主要關注它的參數以及返回值。java
pageNumber
、pageSize
等),這樣,Jpa就可以經過pageable參數來獲得一個帶分頁信息的Sql語句。Spring Data Jpa除了會經過命名規範幫助咱們擴展Sql語句外,還會幫助咱們處理類型爲Pageable
的參數,將pageable參數轉換成爲sql'語句中的條件,同時,還會幫助咱們處理類型爲Page
的返回值,當發現返回值類型爲Page
,Spring Data Jpa將會把數據的總體信息、當前數據的信息,分頁的信息都放入到返回值中。這樣,咱們就可以方便的進行個性化的分頁查詢。spring
分頁:sql
package org.springdata.repository;
import org.springdata.domain.Employee; import org.springframework.data.repository.PagingAndSortingRepository; /** */ public interface EmployeePadingAndSortingResponstory extends PagingAndSortingRepository<Employee,Integer> { }
編寫測試類dom
package org.springdata.crudservice;
import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springdata.domain.Employee; import org.springdata.repository.EmployeePadingAndSortingResponstory; import org.springdata.service.CrudEmployeeService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import java.util.List; /** */ public class PagingAndSortingRespositoryTest { private ApplicationContext ctx = null; private EmployeePadingAndSortingResponstory employeePadingAndSortingResponstory = null; @Before public void setup(){ ctx = new ClassPathXmlApplicationContext("beans_news.xml"); employeePadingAndSortingResponstory = ctx.getBean(EmployeePadingAndSortingResponstory.class); System.out.println("setup"); } @After public void tearDown(){ ctx = null; System.out.println("tearDown"); } @Test public void testPage(){ //index 1 從0開始 不是從1開始的 Pageable page = new PageRequest(0,10); Page<Employee> employeeList = employeePadingAndSortingResponstory.findAll(page); System.out.println("查詢總頁數:"+employeeList.getTotalPages()); System.out.println("查詢總記錄數:"+employeeList.getTotalElements()); System.out.println("查詢當前第幾頁:"+employeeList.getNumber()+1); System.out.println("查詢當前頁面的集合:"+employeeList.getContent()); System.out.println("查詢當前頁面的記錄數:"+employeeList.getNumberOfElements()); } }
查詢結果 我們先在Employee 實體類 重寫下toString()方法 才能打印集合數據測試
排序:spa
基於上面的查詢集合 咱們新建一個測試方法code
@Test
public void testPageAndSord(){ //根據id 進行降序 Sort.Order order = new Sort.Order(Sort.Direction.DESC,"id"); Sort sort = new Sort(order); //index 1 從0開始 不是從1開始的 Pageable page = new PageRequest(0,10,sort); Page<Employee> employeeList = employeePadingAndSortingResponstory.findAll(page); System.out.println("查詢總頁數:"+employeeList.getTotalPages()); System.out.println("查詢總記錄數:"+employeeList.getTotalElements()); System.out.println("查詢當前第幾頁:"+employeeList.getNumber()+1); System.out.println("查詢當前頁面的集合:"+employeeList.getContent()); System.out.println("查詢當前頁面的記錄數:"+employeeList.getNumberOfElements()); }
咱們能夠看到 最大id 排前面了xml