springboot-data-jpa常用排序方法彙總

springboot-data-jpa默認方法支持排序,當然複雜的場景需要自己重寫默認的方法,下面介紹四種常用的排序方法

首先需要定義一個依賴的對象

@Data
public class Person{

 private Integer id;
 
 private String name;

 private int sex;

 private String address;
 
}

定義Repository

@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
   ///方法的定義
}


  • 自定義接口
    如果我們只需要做簡單查詢,其中一個字段需要作爲排序,則可以使用jpa支持自定義接口的辦法即可
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
    findByNameOrderByIdDesc(String name);
    findByNameOrderByIdAsc(String name);
}

使用該方法的好處是業務邏輯代碼簡單,缺點是可擴展性不太好,支持升序或者降序操作,當一個接口需要同時支持升序或者降序時,則不適用。


  • @query接口
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
    @Query(" from Person WHERE name = ?1 ORDER BY id ?2")
    List<Person> findInOrders(String name, String order);
}

使用該方法還是隻能支持單個字段排序,優點是業務邏輯代碼簡單,另外比上一種更靈活,同時支持升序和降序排序。


  • Sort方法
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
   
    List<Person > findByname(String name, Sort sort)
}

使用該方法支持多個字段排序,優點是業務邏輯代碼簡單,代碼看上去更優雅,同時支持升序和降序排序。缺點是所有字段必須同時支持同一種排序方式


除了上述三種方式外,還有支持複雜的查詢及排序

  • 接口重寫
    需要繼承接口JpaSpecificationExecutor
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer>, JpaSpecificationExecutor<Person> {  
  
}

在服務實現類裏面需要重寫toPredicate方法

public class PersonServiceImpl{
  PersonRepository  repository;
   findByCond(Condition cond){
      repository.findAll(new Specification<Person>(){
        PageRequest pageable = new PageRequest(cond.page, cond.size);
         @Override
          public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
          //業務邏輯代碼
       }, pageable)       
  }    
}

該方法最大的優勢是可擴展性非常的高,可以添加多條件,同時支持多字段排序字段,每個字段的排序規則根據實際情況可以自由變化。
好了,先分享到這裏

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