例如需要實現一個形如下面的sql:
select * from table where a='a' and b='b' order by c asc,d desc;
就是根據兩個條件進行排序。
在spring data for jpa 中,存在一個pageable接口,是對查詢分頁的一個利器。
pageable實現類的構造方法中有個Sort參數,可以按照列屬性進行排序。通過查看Sort類的構造方法,我們對Sort這個類進行一下分析,Sort類中存在一下幾個構造方法:
1.public Sort(Order... orders);
2.public Sort(List<Order> orders);
3.public Sort(String... properties);
4.public Sort(Direction direction, String... properties);
5.public Sort(Direction direction, List<String> properties);
大概這幾種構造方法,其中
Direction
是用來標識按照列屬性升序還是降序排序的。
properties即為列屬性。
因為我們要排列的兩個屬性升序和降序都存在,4、5方法由於只能夠實用一種排序方向,所以不能采用。
方法3只是輸入列屬性,按照默認的排序方式(ASC),因此也不能滿足要求。
接下來我們看構造方法1和2,性質相同,主要是Order類的用途是怎樣的。
看一下Order類的構造方法:
public
Order(Direction direction, String property);
可以看到一個Order維護一個
Direction
和一個列屬性,正式我們所要的。
所以采用如下的方法:
List< Order> orders=new ArrayList< Order>();
orders.add( new Order(Direction. ASC, "c"));
orders.add( new Order(Direction. DESC, "d"));
Pageable pageable= new PageRequest(pageNumber, pageSize, new Sort(orders));
jpaRepo.findByAAndB(a,b,pageable);