SpringDataJPA 之 PagingAndSortingRepository 接口

轉載自:https://cloud.tencent.com/developer/article/1429321

敘述

PagingAndSortingRepository 接口繼承於 CrudRepository 接口,擁有CrudRepository 接口的所有方法, 並新增兩個功能:分頁和排序。 但是這兩個方法不能包含篩選條件。

解決方案

PagingAndSortingRepository接口

接口聲明

/**
 * PagingAndSortingRepository 接口使用
 * 定義的方法名稱 參考文檔定義
 * 提供分頁和排序功能
 */
public interface UserDao extends PagingAndSortingRepository<Users,Integer> {

}

分頁功能

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDemo {

    @Autowired
    private UserDao usersDao;


    /**
     * 分頁
     */
    @Test
    public void test1(){
        int page = 0; //page:當前頁的索引。注意索引都是從 0 開始的。
        int size = 3;// size:每頁顯示 3 條數據
        PageRequest pageable= new PageRequest(page, size);
        Page<Users> p = this.usersDao.findAll(pageable);
        System.out.println("數據的總條數:"+p.getTotalElements());
        System.out.println("總頁數:"+p.getTotalPages());
        List<Users> list = p.getContent();
        for (Users users : list) {
            System.out.println(users);
        }
    }
 }

排序功能

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestDemo {

    @Autowired
    private UserDao usersDao;


    /**
     * 對單列做排序處理
     */
    @Test
    public void test2(){
        //Sort:該對象封裝了排序規則以及指定的排序字段(對象的屬性來表示)
        //direction:排序規則
        //properties:指定做排序的屬性
        Sort sort = new Sort(Sort.Direction.DESC,"userid");
        List<Users> list = (List<Users>)this.usersDao.findAll(sort);
        for (Users users : list) {
            System.out.println(users);
        }
    }
    /**
     * 多列的排序處理
     */
    @Test
    public void test3(){
        //Sort:該對象封裝了排序規則以及指定的排序字段(對象的屬性來表示)
        //direction:排序規則
        //properties:指定做排序的屬性
        Sort.Order order1 = new Sort.Order(Sort.Direction.DESC,"userage");
        Sort.Order order2 = new Sort.Order(Sort.Direction.ASC,"username");
        Sort sort = new Sort(order1,order2);
        List<Users> list = (List<Users>)this.usersDao.findAll(sort);
        for (Users users : list) {
            System.out.println(users);
        }
    }
}

單條件排序

多條件排序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章